C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Note: The Try block is required to use a Catch block. If we use no try nor catch, the exception is still thrown.
But: If we do not use a Catch statement, and none is found in calling methods, the exception will cause the program to terminate.
VB.NET program that uses Try, Catch
Module Module1
Sub Main()
Try
' Try to divide by zero.
Dim value As Integer = 1 / Integer.Parse("0")
' This statement is sadly not reached.
Console.WriteLine("Hi")
Catch ex As Exception
' Display the message.
Console.WriteLine(ex.Message)
End Try
End Sub
End Module
Output
Arithmetic operation resulted in an overflow.
VB.NET program that uses Throw statement
Module Module1
Sub Main()
Try
' Throw a serious exception.
Throw New Exception("Mega-error")
Catch ex As Exception
' Display the exception's message.
Console.WriteLine(ex.Message)
End Try
End Sub
End Module
Output
Mega-error
However: It is more efficient to simply check for Nothing, with the "Not Nothing" construct. More information on Nothing is available.
NothingIf ThenCode that causes NullReferenceException: VB.NET
Dim value As String = Nothing
Console.WriteLine(value.Length)
Exception text:
Unhandled Exception: System.NullReferenceException:
Object reference not set to an instance of an object.
Code that avoids exception: VB.NET
Dim value As String = Nothing
If Not value Is Nothing Then
Console.WriteLine(value.Length)
End If
So: One strategy is to reserve exceptions for "exceptional" conditions, not normal ones. If a value may be zero, check it before dividing.
However: If an important file is missing from your program's setup, an exception is warranted. This is an exceptional condition.
And: Finally statements are run after catch blocks are reached. It can be used to execute cleanup code.
Tip: The Using-statement, which ensures cleanup of resources, is implemented with the Finally statement. It is a form of syntactic sugar.
Here: In this example, all 5 Console.WriteLine calls are reached. An exception is triggered in the Try-block.
Then: The Catch-block's statements are executed. And finally, the Finally statement is reached.
VB.NET program that uses Finally
Module Module1
Sub Main()
Console.WriteLine(0)
Try
' Reached.
Console.WriteLine(1)
' An exception is thrown.
Dim s As String = Nothing
s = s.ToUpper()
Catch ex As Exception
' Reached.
Console.WriteLine(2)
Finally
' Reached.
Console.WriteLine(3)
End Try
Console.WriteLine(4)
End Sub
End Module
Output
0
1 [in Try]
2 [in Catch]
3 [in Finally]
4