Exception Handling in VB.Net
If you are new to VB.Net School
This is the 9th in the series of lessons of our VB.Net School. The VB.Net School is a kind of interactive learning platform where those who want to learn .NET with VB.Net can find help and support. With one issue a week, describing some areas of the VB.Net Programming Language with the Microsoft .Net Platform, this is not the same traditional passive tutorial where the author only writes and the reader only reads. There will be exercise problems at the end of each issue, which the reader is expected to solve after reading the issue. The solution to these problems will be provided in the next issue for testing purposes. There is also a dedicated
message board attached with the school, where you can ask questions about the article, and the author will respond to your question within 2/3 days. You can send your suggestions, feedback or ideas on how these lessons can be improved to either the Author (
farazrasheed@acm.org) or the WEBMASTER (
info@programmersheaven.com).
For previous lessons click
here
Lesson Plan
Shortly we will explore the exception handling mechanism in VB.Net. We will start by looking at the idea behind exceptions and how different exceptions are caught. Later we will explore the different features provided and the constraints applied by the VB.Net programming language in exception handling. Finally we will learn how to define our own custom exceptions.
Exceptions Basics
Exception handling is a mechanism to manage run-time errors in .NET that would otherwise cause your software to terminate abruptly.
The need for Exceptions
Consider the following simple code
Imports System
Module Test
Public Sub Main()
Dim p As Integer = ConvertToInteger("34")
Console.WriteLine(p)
End Sub
Public Function ConvertToInteger(ByVal str As String) As Integer
Dim i As Integer = Integer.Parse(str)
Return i
End Function
End Module
The
ConvertToInteger() method returns the integer present in the string type. The output of this code will be
34
But what if the method
ConvertToInteger() is called in the
Main() method as
Dim p As Integer = ConvertToInteger("My name")
There won't be a compile time error as the parameter 'My name' is in the required form of a string. However when the code is executed, the processor will attempt to convert the string 'My name' to an Integer which is offcourse not possible. The result, the program will crash! What should we do now?
Exceptions in VB.Net and .Net Framework
People have worked on the problem of managing errors and have developed a solution in the form of 'Exceptions'. Programmers may define and throw an exception in the case of unexpected events. Below are some important points about exceptions and the exception handling mechanism in VB.Net and the .Net Framework:
- All exceptions in .Net are objects.
- The System.Exception class is the base class for all the exceptions in .Net
- Any method can raise or throw an exception in the case of some unexpected event during its execution using the throw keyword in VB.Net
- The thrown exception can be caught or dealt within the calling method using the Try...Catch block.
- The code that may throw an exception which we want to handle is put in the Try block. This is called an attempt to catch an exception.
- The code to handle the thrown exception is placed in the Catch block just after the Try block. This is called catching an exception. We can define which particular class of exception we want to deal in this Catch block by mentioning the name of the exception with the Catch keyword
- Multiple Catch blocks can be defined for a single Try block where each Catch block will Catch a particular class of exception.
- The code that must always be executed after the Try or Try...Catch block is placed in the Finally block. This is just after the Try or the Try...Catch block. This code is guaranteed to always be executed whether the exception occurs or not.
- When an exception is raised during the execution of code inside the Try block, the remaining code in the Try block is neglected and the control of execution is transferred to the respective Catch or Finally block.
- Since exceptions are present in .Net as classes and objects they follow the inheritance hierarchy. This means that if you write a Catch block to handle a base class exception, it will automatically handle all of its sub-class exceptions. Attempting to Catch any of the sub-class exceptions explicitly after the parent class exception will make render your code unreachable or useless.
- The Finally block is optional. Exception handling requires any combination of the Try...Catch or Try...Catch...Finally or Try...Finally blocks.
- If you do not Catch an exception the runtime environment (Common Language Runtime or CLR) will Catch it on your behalf and may cause your program to be terminated.
Author's Note: For VB6 developers, Try...Catch is .Net's replacement for On Error and is much more structured as you will see in this lesson. For Java developers, there is no concept of checked exceptions in VB.Net. All the exceptions are implicitly unchecked. Hence there is no throws keyword present in VB.Net. The absence of checked exceptions in VB.Net is quite a hot topic of debate since the birth of .Net. I personally feel that the idea of checked exceptions is extremely good and it should have been implemented in VB.Net. See the Microsoft web site regards the argument of Hejlsberg and other designers of C# and why they haven't included checked exceptions in .Net
http://msdn.microsoft.com/chats/vstudio/vstudio_032103.asp
Handling Exceptions using the Try...Catch...Finally blocks
Use of the Try...Catch block
A simple demonstration for the use of
Try...Catch block is given below
Public Sub Main()
Dim s As String = Nothing
Try
Console.WriteLine("In Try block... before calling s.ToLower()")
Console.WriteLine(s.ToLower())
Console.WriteLine("In Try block... after calling s.ToLower()")
Catch e As NullReferenceException
Console.WriteLine("In Catch block...")
Console.WriteLine("NullReferenceException Caught")
End Try
Console.WriteLine("After Try...Catch block")
End Sub
The string 's' in the
Main() method is assigned a Nothing value. If we attempt to call the
ToLower() method with this null reference in the
Console.WriteLine() method, the CLR (Common Language Runtime) will raise the
NullReferenceException. Since we have enclosed the call to the
ToLower() method in a
Try block, the Runtime will search for a
Catch block which can Catch this exception and, if one is found, the execution will jump to this
Catch block. The syntax of the
Catch block is important to understand. After the
Catch, a reference ('e' in our case) of our target exception class is declared (
NullReferenceException in our case). When the above program is executed, the outputs is
In Try block... before calling s.ToLower()
In Catch block...
NullReferenceException Caught
After Try...Catch block
Press any key to continue
Carefully look at the output of the program and compare it with the source code. The call to
s.ToLower() raised the
NullReferenceException. As a result the execution of the remaining part of the
Try block is ignored and the program execution is transferred to the
Catch block. Remember that the
NullReferenceException is raised when we attempt to access the members of a class using a null reference (
Nothing). Lets change the code above a little and assign an object to the reference 's'
Public Sub Main()
Dim s As String = "Faraz"
Try
Console.WriteLine("In Try block... before calling s.ToLower()")
Console.WriteLine(s.ToLower())
Console.WriteLine("In Try block... after calling s.ToLower()")
Catch e As NullReferenceException
Console.WriteLine("In Catch block...")
Console.WriteLine("NullReferenceException Caught")
End Try
Console.WriteLine("After Try...Catch block")
End Sub
Since this code does not cause any exceptions to be raised, the execution of program will output as
In Try block... before calling s.ToLower()
faraz
In Try block... after calling s.ToLower()
After Try...Catch block
Press any key to continue
Home