「VB.NET」独自の例外Exceptionを作成する

2021年9月14日

構文
Public class 独自の例外クラス名
Inherits Exception
//処理コード
End Class
使用例

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
'独自のExceptionクラスの定義
Public Class SampleException
Inherits Exception
Sub New(ByVal cft As String)
'基底クラスMyBaseを参照
MyBase.New(cft)
End Sub
End Class
Module Module1
Sub Main()
Dim cftA As Integer = 99
'try catch例外の処理
Try
Dim result As Integer
'関数funcAを呼び出す
result = funcA(cftA)
Catch ex As SampleException
'独自の例外SampleExceptionのメッセージを出力
Console.WriteLine(ex.Message)
Finally
'Finally処理
Console.WriteLine("例外処理が終了しました")
End Try
Console.ReadKey()
End Sub
'関数funcAの定義
Private Function funcA(ByVal cftA As Integer) As Integer
If cftA = 99 Then
'Throw文で独自の例外SampleExceptionを投げる
Throw New SampleException("独自例外定義のサンプル 123456")
End If
Return cftA * 2
End Function
End Module
'独自のExceptionクラスの定義 Public Class SampleException Inherits Exception Sub New(ByVal cft As String) '基底クラスMyBaseを参照 MyBase.New(cft) End Sub End Class Module Module1 Sub Main() Dim cftA As Integer = 99 'try catch例外の処理 Try Dim result As Integer '関数funcAを呼び出す result = funcA(cftA) Catch ex As SampleException '独自の例外SampleExceptionのメッセージを出力 Console.WriteLine(ex.Message) Finally 'Finally処理 Console.WriteLine("例外処理が終了しました") End Try Console.ReadKey() End Sub '関数funcAの定義 Private Function funcA(ByVal cftA As Integer) As Integer If cftA = 99 Then 'Throw文で独自の例外SampleExceptionを投げる Throw New SampleException("独自例外定義のサンプル 123456") End If Return cftA * 2 End Function End Module
'独自のExceptionクラスの定義
Public Class SampleException
    Inherits Exception

    Sub New(ByVal cft As String)
        '基底クラスMyBaseを参照
        MyBase.New(cft)
    End Sub

End Class


Module Module1

    Sub Main()
        Dim cftA As Integer = 99

        'try catch例外の処理
        Try
            Dim result As Integer

            '関数funcAを呼び出す
            result = funcA(cftA)

        Catch ex As SampleException
            '独自の例外SampleExceptionのメッセージを出力
            Console.WriteLine(ex.Message)

        Finally
            'Finally処理
            Console.WriteLine("例外処理が終了しました")
        End Try

        Console.ReadKey()

    End Sub

    '関数funcAの定義
    Private Function funcA(ByVal cftA As Integer) As Integer

        If cftA = 99 Then
            'Throw文で独自の例外SampleExceptionを投げる
            Throw New SampleException("独自例外定義のサンプル 123456")
        End If

        Return cftA * 2
    End Function


End Module

実行結果
独自例外定義のサンプル 123456
例外処理が終了しました

VB.net

Posted by arkgame