Exception Handling In VB.NET
What is Exception Handling?
Explanation
Exception Handling in vb.net 2008.
Exceptions Handling are errors that are triggered at runtime, that are handled in VB.net using structured
error handling with the
Try..Catch..Finally statement. The
On erro goto,
On Error Resume Next statement is used
for unstructured error handling.
The exceptions can be handled in the
Try..Catch..finally using the
Built-in exception handling methods.
Example1:
Module Module1
Sub Main()
Dim a(3) As Integer
Try
a(5) = 45
Catch ex As IndexOutOfRangeException
Console.WriteLine(ex.Message)
Catch ex As Exception
Console.WriteLine(ex.Message)
Finally
Console.WriteLine("End of Execution")
End Try
Console.Read()
End Sub
End Module
Result:
Index was outside the bounds of the array
End of Execution
Description:
In the above example, the dimension of the array declared is '3' and the array given array under the
Try statement is '5'. The exception is caught by the catch statement using the specific exception option
IndexOutOfRangeException and even the
Exception option display messages for all exceptions.
On Error Goto Statement:
Example2:
Module Module1
Sub Main()
Dim i, j As Integer
For i = 0 To 10 Step 1
On Error GoTo ErrorHandler
j = 100 / i
Console.WriteLine("Value of j is::")
Console.WriteLine(j)
Next
ErrorHandler:
Console.WriteLine("Division by zero error")
Console.Read()
End Sub
End Module
Result:
Division by zero error
On Error Goto Statement:
In the above example the ustructured error handling statement
On Error Goto is used
along with the
ErrorHandler to display the error message that diverts the flow of the program itself.
Example3:
Module Module1
Public Class student
Public Function Add(ByVal i As Integer,
ByVal j As Integer) As Integer
Console.WriteLine("Result:"(i / j))
End Function
End Class
Sub Main()
On Error Resume Next
Dim obj As New student
obj.Add(10, 0)
Console.WriteLine("Check the Arguments")
Console.Read()
End Sub
End Module
Result:
Check the Arguments
In the above the example when the exception occurs the flow of the program is continued from the
next line.