Chapter Four
Chapter Four
Exceptions provide a way to transfer control from one part of a program to another. VB.Net
exception handling is built upon four keywords - Try, Catch, Finally and Throw.
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.
Throw − A program throws an exception when a problem shows up. This is done
using a Throw keyword.
4.2 Structured Exception Handling
VB.NET utilizes the .NET Framework’s standard mechanism for error reporting, called
Structured Exception Handling; it relies on exceptions to report errors that arise in applications.
Exceptions are classes that trap the error information. To utilize .NET’s Structured Exception
Handling mechanisms properly, developers need to write smart code that watches out for
exceptions and implement code to deal with these exceptions.
The following table provides some of the predefined exception classes derived from the
Sytem.SystemException class −
End Module
Example 2:
Module Module1
Sub division(ByVal n1 As Integer, ByVal n2 As Integer)
Dim answer As Integer
Try
answer = n1 \ n2
Catch ex As DivideByZeroException
Console.WriteLine("Exception: {0}", ex)
Finally
Console.WriteLine("Answer is: {0}", answer)
End Try
End Sub
Sub Main()
division(4, 0)
Console.ReadKey()
End Sub
End Module