サンプルコードの共通(例外処理)
当サンプルの中の Windows アプリケーションにおいて、アプリケーションのエントリポイント等で、
Application.ThreadException イベントに
ハンドラを追加している箇所がありますが、
共通してここで紹介するハンドラを使用しています。
また、業務的なエラーの場合に投げる例外もここで紹介します。
サンプルのプロジェクトダウンロード
■クラス図
クラス図です。
準備中...
■コード
Application.ThreadException イベント をハンドリングするメソッドを持つクラスです。
ExceptionHandler.vb
Imports System.Windows.Forms Public Class ExceptionHandler '共通 例外ハンドラ Public Shared Sub MyHandler(ByVal sender As Object, ByVal t As System.Threading.ThreadExceptionEventArgs) If TypeOf t.Exception Is MyException Then '自前の例外の場合はメッセージ表示のみ MessageBox.Show(t.Exception.Message, _ t.Exception.GetType().Name, _ MessageBoxButtons.OK, _ MessageBoxIcon.Exclamation) Else Dim result As DialogResult = System.Windows.Forms.DialogResult.Cancel Try result = ShowThreadExceptionDialog(t.Exception) Catch Try MessageBox.Show("Fatal Error", _ "Fatal Error", _ MessageBoxButtons.OK, _ MessageBoxIcon.Stop) Finally Application.Exit() End Try End Try If (result = System.Windows.Forms.DialogResult.OK) Then Application.Exit() End If End If End Sub '例外の詳細情報を表示する Private Shared Function ShowThreadExceptionDialog(ByVal e As Exception) As DialogResult Dim targetex As Exception Dim cnt As Integer = 1 Dim errorMsg As System.IO.StringWriter = New System.IO.StringWriter targetex = e Do While Not IsNothing(targetex) With errorMsg .WriteLine("==================================================") .WriteLine("No:" + cnt.ToString) .WriteLine("(呼び出しスタック)" + targetex.Source) .WriteLine("(内部メッセージ )" + targetex.Message) If Not IsNothing(targetex.TargetSite) Then .WriteLine("(発生メソッド )" + targetex.TargetSite.Name) Else .WriteLine("(発生メソッド )" + "") End If .WriteLine("(スタックトレース)" + targetex.StackTrace) End With targetex = targetex.InnerException cnt += 1 Loop Return MessageBox.Show(errorMsg.ToString(), _ "アプリケーション エラー", _ MessageBoxButtons.OK, _ MessageBoxIcon.Stop) End Function End Class
自前の例外クラスです。
MyException.vb
'自前の例外 Public Class MyException Inherits Exception 'コンストラクタ Public Sub New(ByVal message As String) MyBase.New(message) End Sub End Class