Imports System.Threading Public Class Program _ Shared Sub Main() ' ThreadExceptionイベント・ハンドラを登録する AddHandler Application.ThreadException, AddressOf Application_ThreadException ' UnhandledExceptionイベント・ハンドラを登録する AddHandler Thread.GetDomain().UnhandledException, AddressOf Application_UnhandledException ' メイン・スレッド以外の例外はUnhandledExceptionでハンドルする 'Dim buffer As String = "1" 'Dim [error] As Char = buffer.Chars(2) ' ここで実行されるメイン・アプリケーション・スレッドの例外は ' Application_ThreadExceptionでハンドルできる Application.Run(New Form1) End Sub ' 未処理例外をキャッチするイベント・ハンドラ(Windowsアプリケーション用) Public Shared Sub Application_ThreadException(ByVal sender As Object, ByVal e As ThreadExceptionEventArgs) ShowErrorMessage(e.Exception, "Application_ThreadExceptionによる例外通知です。") End Sub ' 未処理例外をキャッチするイベント・ハンドラ(主にコンソール・アプリケーション用) Public Shared Sub Application_UnhandledException(ByVal sender As Object, ByVal e As UnhandledExceptionEventArgs) Dim ex As Exception = CType(e.ExceptionObject, Exception) If Not ex Is Nothing Then ShowErrorMessage(ex, "Application_UnhandledExceptionによる例外通知です。") End If End Sub ' ユーザー・フレンドリなダイアログを表示するメソッド Public Shared Sub ShowErrorMessage(ByVal ex As Exception, ByVal extraMessage As String) MessageBox.Show(extraMessage & vbLf & "――――――――" & vbLf & vbLf & _ "エラーが発生しました。開発元にお知らせください" & vbLf & vbLf & _ "【エラー内容】" & vbLf & ex.Message & vbLf & vbLf & _ "【スタックトレース】" & vbLf & ex.StackTrace) End Sub End Class