Exceptions are runtime errors that occur when a program is running and causes the program to abort without execution.
Such kind of situations can be handled using Exception Handling.
By placing specific lines of code in the application we can handle most of the errors that we may encounter and we can enable the application to continue running.
VB .NET supports two ways to handle exceptions,
Unstructured exception Handling using the on error goto statement and
Structured exception handling using Try....Catch.....Finally
Let's look at the new kind of exception handling introduced in VB .NET which is the Structured Exception Handling. VB .NET uses Try....Catch....Finally block type exception handling.
The syntax looks like this:
Module Module1
Sub Main()
Try
--
Catch e as Exception
--
Finally
End Try
End Sub
End Module
Example
Imports System.Console
Module Module1
Sub Main()
Dim a = 0, b = 1, c As Integer
Try
c = b / a'the above line throws an exception
WriteLine("C is " & c)
Catch e As Exception
WriteLine(e)'catching the exception
End Try
End Sub
End Module
The output of the above code displays a message stating the exception. The reason for the exception is because any number divided by zero is infinity.
When working with Structured exception handling you can have multiple Catch blocks to handle different types of exceptions differently. The code in the Finally block is optional. If there is a Finally block in the code then that code is executed last.
-
