Exception Handling 2023
Exception Handling 2023
3 Exception handling
Catch ex As Exception The Catch word means "Catch any errors here".
Exception handling:
Try: A Try block identifies a block of code for which particular exceptions will be
activated.
It's followed by one or more Catch blocks.
Catch: A program catches an exception with an exception handler at the place in a
program where you want to handle the problem.
The Catch keyword indicates the catching of an exception.
Finally: The Finally block is used to execute a given set of statements, whether an
exception is thrown or not thrown.
For example, if you open a file, it must be closed whether an exception is
raised or not.
Syntax
Try
[ tryStatements ]
[ Exit Try ]
[ Catch [ exception [ As type ] ] [ When expression ]
[ catchStatements ]
[ Exit Try ] ]
[ Catch ... ]
[ Finally
[ finallyStatements ] ]
End Try
Module exceptionProg
Sub division(ByVal num1 As Integer, ByVal num2 As Integer)
Dim result As Integer
Try
result = num1 \ num2
Catch e As DivideByZeroException
Console.WriteLine("Exception caught: {0}", e)
Finally
Console.WriteLine("Result: {0}", result)
End Try
End Sub
Sub Main()
division(25, 0)
Console.ReadKey()
End Sub
End Module
An example of throwing an exception when dividing by zero condition occurs:
Module exceptionProg
Public Class TempIsZeroException : Inherits ApplicationException
Public Sub New(ByVal message As String)
MyBase.New(message)
End Sub
End Class
Public Class Temperature
Dim temperature As Integer = 0
Sub showTemp()
If (temperature = 0) Then
Throw (New TempIsZeroException("Zero
Temperature found"))
Else
Console.WriteLine("Temperature: {0}",
temperature)
End If
End Sub
End Class
Sub Main()
Dim temp As Temperature = New Temperature()
Try
temp.showTemp()
Catch e As TempIsZeroException
Console.WriteLine("TempIsZeroException: {0}", e.Message)
End Try
Console.ReadKey()
End Sub
End Module
Throwing Objects
You can throw an object if it is either directly or indirectly derived from the
System.Exception class.
Module
You exceptionProg
can use a throw statement in the catch block to throw the present object as:
Sub Main()
Try
Throw New ApplicationException("A custom exception _ is being
thrown here...")
Catch e As Exception
Console.WriteLine(e.Message)
Finally
Console.WriteLine("Now inside the Finally Block")
End Try
Console.ReadKey()
End Sub
End Module