[VB.NET]Throw New Exceptionで例外を投げるサンプル

2021年10月4日

書式

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
If 条件式 Then
Throw New Exception(文字列)
Exit Function
End If
If 条件式 Then Throw New Exception(文字列) Exit Function End If
If 条件式 Then
  Throw New Exception(文字列)
  Exit Function
End If

使用例

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
Imports System.IO
Imports System.Text
Module Module1
Sub Main()
'Integer型変数の宣言
Dim res As Integer = 3
'Boolean型変数の宣言
Dim res2 As Boolean
'Try Catchの定義
Try
'関数TestFuncを呼び出す
res2 = TestFunc(res)
Catch ex As Exception
'メッセージを出力
Console.WriteLine(ex.Message)
Finally
'Finally処理
Console.WriteLine("Finally処理が終了しました study skill")
End Try
Console.WriteLine("戻り値: " + res2.ToString)
Console.ReadKey()
End Sub
'Function関数TestFuncの定義
Private Function TestFunc(ByVal result As Integer) As Boolean
'If判定
If result <> 1 Then
'例外Exceptionを投げる
Throw New Exception("エラーコード:" & result)
'戻り値がFalse
Return False
'Function修了
Exit Function
End If
Return True
End Function
End Module
Imports System.IO Imports System.Text Module Module1 Sub Main() 'Integer型変数の宣言 Dim res As Integer = 3 'Boolean型変数の宣言 Dim res2 As Boolean 'Try Catchの定義 Try '関数TestFuncを呼び出す res2 = TestFunc(res) Catch ex As Exception 'メッセージを出力 Console.WriteLine(ex.Message) Finally 'Finally処理 Console.WriteLine("Finally処理が終了しました study skill") End Try Console.WriteLine("戻り値: " + res2.ToString) Console.ReadKey() End Sub 'Function関数TestFuncの定義 Private Function TestFunc(ByVal result As Integer) As Boolean 'If判定 If result <> 1 Then '例外Exceptionを投げる Throw New Exception("エラーコード:" & result) '戻り値がFalse Return False 'Function修了 Exit Function End If Return True End Function End Module
Imports System.IO
Imports System.Text

Module Module1

    Sub Main()
        'Integer型変数の宣言
        Dim res As Integer = 3
        'Boolean型変数の宣言
        Dim res2 As Boolean

        'Try Catchの定義
        Try
            '関数TestFuncを呼び出す
            res2 = TestFunc(res)
        Catch ex As Exception
            'メッセージを出力
            Console.WriteLine(ex.Message)
        Finally
            'Finally処理
            Console.WriteLine("Finally処理が終了しました study skill")
        End Try

        Console.WriteLine("戻り値: " + res2.ToString)

        Console.ReadKey()
    End Sub

    'Function関数TestFuncの定義 
    Private Function TestFunc(ByVal result As Integer) As Boolean
        'If判定
        If result <> 1 Then
            '例外Exceptionを投げる
            Throw New Exception("エラーコード:" & result)
            '戻り値がFalse
            Return False
            'Function修了
            Exit Function
        End If

        Return True
    End Function

End Module

実行結果
エラーコード:3
Finally処理が終了しました study skill
戻り値: False

VB.net

Posted by arkgame