Search This Blog

Most Viewed

Sunday, March 13, 2011

Exception Handling in VB.Net





Exception handling is an in built mechanism in .NET framework to detect and handle run time errors. The .NET framework contains lots of standard exceptions. The exceptions are anomalies that occur during the execution of a program. They can be because of user, logic or system errors. If a user (programmer) do not provide a mechanism to handle these anomalies, the .NET run time environment provide a default mechanism, which terminates the program execution.


VB.NET provides three keywords try, catch and finally to do exception handling. The try encloses the statements that might throw an exception whereas catch handles an exception if one exists. The finally can be used for doing any clean up process.



The general form try-catch-finally in VB.NET is shown below.


Try

' Statement which can cause an exception.

Catch x As Type
' Statements for handling the exception
Finally
End Try 'Any cleanup code

If any exception occurs inside the try block, the control transfers to the appropriate catch block and later to the finally block.



But in VB.NET, both catch and finally blocks are optional. The try block can exist either with one or more catch blocks or a finally block or with both catch and finally blocks.  



If there is no exception occurred inside the try block, the control directly transfers to finally block. We can say that the statements inside the finally block is executed always. Note that it is an error to transfer control out of a finally block by using break, continue, return or goto.  



In VB.NET, exceptions are nothing but objects of the type Exception. The Exception is the ultimate base class for any exceptions in VB.NET. The VB.NET itself provides couple of standard exceptions. Or even the user can create their own exception classes, provided that this should inherit from either Exception class or one of the standard derived classes of Exception class like DivideByZeroExcpetion ot ArgumentException etc.  



Uncaught Exceptions  


The following program will compile but will show an error during execution. The division by zero is a runtime anomaly and program terminates with an error message. Any uncaught exceptions in the current context propagate to a higher context and looks for an appropriate catch block to handle it. If it can't find any suitable catch blocks, the default mechanism of the .NET runtime will terminate the execution of the entire program.



//VB.NET: Exception Handling 

Imports System
Class MyClient
Public Shared Sub Main()
Dim x As Integer = 0
Dim div As Integer = 100 / x
Console.WriteLine(div)
End Sub 'Main
End Class 'MyClient

The modified form of the above program with exception handling mechanism is as follows. Here we are using the object of the standard exception class DivideByZeroException to handle the exception caused by division by zero.

//VB.NET: Exception Handling
Imports System
Class MyClient
Public Shared Sub Main()
Dim x As Integer = 0
Dim div As Integer = 0
Try
div = 100 / x
Console.WriteLine("This line in not executed")
Catch de As DivideByZeroException
onsole.WriteLine("Exception occured")
End Try
Console.WriteLine("Result is {0}", div)
End Sub 'Main
End Class 'MyClient 

In the above case the program do not terminate unexpectedly. Instead the program control passes from the point where exception occurred inside the try block to the catch blocks. If it finds any suitable catch block, executes the statements inside that catch and continues with the normal execution of the program statements. 

If a finally block is present, the code inside the finally block will get also be executed.

//VB.NET: Exception Handling
Imports System
Class MyClient
Public Shared Sub Main()
Dim x As Integer = 0
Dim div As Integer = 0
Try
div = 100 / x
Console.WriteLine("Not executed line")
Catch de As DivideByZeroException
Console.WriteLine("Exception occured")
Finally
Console.WriteLine("Finally Block")
End Try
Console.WriteLine("Result is {0}", div)
End Sub 'Main
End Class 'MyClient 

Remember that in VB.NET, the catch block is optional. The following program is perfectly legal in VB.NET.

//VB.NET: Exception Handling
Imports System
Class MyClient
Public Shared Sub Main()
Dim x As Integer = 0
Dim div As Integer = 0
Try
div = 100 / x
Console.WriteLine("Not executed line")
Finally
Console.WriteLine("Finally Block")
End Try
Console.WriteLine("Result is {0}", div)
End Sub 'Main
End Class 'MyClient 

But in this case, since there is no exception handling catch block, the execution will get terminated. But before the termination of the program statements inside the finally block will get executed. In VB.NET, a try block must be followed by either a catch or finally block.  

Multiple Catch Blocks 

A try block can throw multiple exceptions, which can handle by using multiple catch blocks. Remember that more specialized catch block should come before a generalized one. Otherwise the compiler will show a compilation error.

//VB.NET: Exception Handling: Multiple catch
Imports System
Class MyClient
Public Shared Sub Main()
Dim x As Integer = 0
Dim div As Integer = 0
Try
div = 100 / x
Console.WriteLine("Not executed line")
Catch de As DivideByZeroException
Console.WriteLine("DivideByZeroException")
Catch ee As Exception
Console.WriteLine("Exception")
Finally
Console.WriteLine("Finally Block")
End Try
Console.WriteLine("Result is {0}", div)
End Sub 'Main
End Class 'MyClient

Catching all Exceptions

By providing a catch block without a brackets or arguments, we can catch all exceptions occurred inside a try block. Even we can use a catch block with an Exception type parameter to catch all exceptions happened inside the try block since in VB.NET, all exceptions are directly or indirectly inherited from the Exception class. 

//VB.NET: Exception Handling: Handling all exceptions
Imports System
Class MyClient
Public Shared Sub Main()
Dim x As Integer = 0
Dim div As Integer = 0
Try
div = 100 / x
Console.WriteLine("Not executed line")
Catch
End Try
Console.WriteLine("Result is {0}", div)
End Sub 'Main
End Class 'MyClient 

The following program handles all exception with Exception object. 

//VB.NET: Exception Handling: Handling all exceptions
Imports System
Class MyClient
Public Shared Sub Main()
Dim x As Integer = 0
Dim div As Integer = 0
Try
div = 100 / x
Console.WriteLine("Not executed line")
Catch e As Exception
Console.WriteLine("oException")
End Try
Console.WriteLine("Result is {0}", div)
End Sub 'Main
End Class 'MyClient 

Throwing an Exception

In VB.NET, it is possible to throw an exception programmatically. The 'throw' keyword is used for this purpose. The general form of throwing an exception is as follows. 



Throw exception_obj


For example the following statement throw an ArgumentException explicitly. 


Throw New ArgumentException("Exception") 

//VB.NET: Exception Handling:
Imports System
Class MyClient
Public Shared Sub Main()
Try
Throw New DivideByZeroException("Invalid Division")
Catch e As DivideByZeroException
Console.WriteLine("Exception")
End Try

Console.WriteLine("LAST STATEMENT")
End Sub 'Main
End Class 'MyClient 

Re-throwing an Exception

The exceptions, which we caught inside a catch block, can re-throw to a higher context by using the keyword throw inside the catch block. The following program shows how to do this. 

//VB.NET: Exception Handling: Handling all exceptions
Imports System

Class [MyClass]

Public Sub Method()
Try
Dim x As Integer = 0
Dim sum As Integer = 100 / x
Catch e As DivideByZeroException
Throw
End Try
End Sub 'Method
End Class '[MyClass]
Class MyClient
Public Shared Sub Main()
Dim mc As New [MyClass]
Try
mc.Method()
Catch e As Exception
Console.WriteLine("Exception caught here")
End Try
Console.WriteLine("LAST STATEMENT")
End Sub 'Main
End Class 'MyClient 

Standard Exceptions

There are two types of exceptions: exceptions generated by an executing program and exceptions generated by the common language runtime. System.Exception is the base class for all exceptions in VB.NET. Several exception classes inherit from this class including ApplicationException and SystemException. These two classes form the basis for most other runtime exceptions. Other exceptions that derive directly from System.Exception include IOException, WebException etc.

The common language runtime throws SystemException. A user program rather than the runtime throws the ApplicationException. The SystemException includes the ExecutionEngineException, StaclOverFlowException etc. It is not recommended that we catch SystemExceptions nor is it good programming practice to throw SystemExceptions in our applications. 

System.OutOfMemoryException 
System.NullReferenceException 
Syste.InvalidCastException 
Syste.ArrayTypeMismatchException 
System.IndexOutOfRangeException 
System.ArithmeticException 
System.DevideByZeroException 
System.OverFlowException 

User-defined Exceptions

In VB.NET, it is possible to create our own exception class. But Exception must be the ultimate base class for all exceptions in VB.NET. So the user-defined exception classes must inherit from either Exception class or one of its standard derived classes. 


//VB.NET: Exception Handling: User defined exceptions
Imports System

Class MyException

Inherits Exception
Public Sub New(ByVal str As String)
Console.WriteLine("User defined exception")
End Sub 'New
End Class 'MyException
Class MyClient
Public Shared Sub Main()
Try
Throw New MyException("RAJESH")
Catch e As Exception
Console.WriteLine(("Exception caught here" + e.ToString()))
End Try
Console.WriteLine("LAST STATEMENT")
End Sub 'Main
End Class 'MyClient 

Design Guidelines

Exceptions should be used to communicate exceptional conditions. Don't use them to communicate events that are expected, such as reaching the end of a file. If there's a good predefined exception in the System namespace that describes the exception condition-one that will make sense to the users of the class-use that one rather than defining a new exception class, and put specific information in the message. Finally, if code catches an exception that it isn't going to handle, consider whether it should wrap that exception with additional information before re-throwing it.









Exception handling is crucial since the robustness of software depends on how effectively a program deals with exceptions. Basically exceptions are the run time error.

Exception Handling in VB.Net:
Exception handling in VB.Net provides uniform, structured and type-safe handling errors.
  • The System.Exception is the super class of exception.
  • Well-Defined exception classes exist for system level errors- such as overflow, divide-by-zero, and null references- which are treated on par with application's level errors.
  • VB.net contains inner exceptions. When a new exception is thrown from an existing exception, the new exception's inner exception can carry the existing exception.
  • Checked and unchecked statements are used to control overflow checking.
  • An exception raised in VB.NET but handled in a C# program is handled in the same way as one raised in C# but handled in VB.NET. There is a uniform way of handling errors.
VB provides a structured way of handing errors: the block of code where errors accepted is guarded by try-catch blocks where exceptions are handled.
System.Exception Overview:
System.Exception represents errors that occur during application execution. This is the base class for all exception in VB.net, so any other type of exception must be derived from it.

The Exception class is present in the System namespace and in the assembly mscorlib.dll.
Some Important Properties of Exception class:
  • StackTrace This StackTrace property can be used to determine where the error occurred.
  • Message The Message property returns a description to the error's cause.
  • InnerException The InnerException property can be used to create and preserve a series of exceptions during exception handling.
  • HelpLink The HelpLink property can hold a URL to a help file that provides extensive information about the cause of exception.
Exception Statements in VB.Net:
VB.Net supports structured exception handling. In structured exception handing, we write code surrounded by blocks. If an exception occurs, the block throws the execution control to a predefined handled code, the try, catch, finally statements define these blocks. In other words, if an application handles exceptions that occur during the execution of a block of application code, the code must be placed with in a try statement.
Application code with in a try statement is a try block. Application code that handles exceptions thrown by a try block is placed with in catch statement and is called a catch block.
In a try block, we define the code we want to execute and protect from any possible errors. The catch block defines the handlers for the exception. The finally block is used to free resources allocated in the try block.
The try statement provides a mechanism to capture exceptions in a block of code and a mechanism to execute blocks of code both under normal circumstances and when an exception occurs.
We can define try statement in a few different forms:
  • try-catch
  • try-finally
  • try-catch-finally
If there is no exception then catch block will not execute but finally will surely execute either there is exception or not in try block.
Let see the exception handling with this program.
Here in this program, I am accepting two numbers from the user and I am dividing the first number from the second number, here if second number is zero then it will throw a DivideByZeroException.
The form 1 designed is:
 
Figure 1:
The form.vb code is:
Imports System
Imports System.Collections.Generic
Imports System.ComponentModel
Imports System.Data
Imports System.Drawing
Imports System.Text
Imports System.Windows.Forms

Namespace AnExceptionHandlingExamle
Public Partial Class Form1 Inherits Form
        Public Sub New()
            InitializeComponent()
        End Sub

        Private Sub button1_Click(ByVal sender As ObjectByVal e As EventArgs)
            MyException(Int32.Parse(textBox1.Text), Int32.Parse(textBox2.Text))
        End Sub

        Public Sub MyException(ByVal a As Int32, ByVal b As Int32)
            Dim Result As Int32
            Try
                'The try block from where an exception will thrown
                Result = a / b
                textBox3.Text = Result.ToString()
            Catch e As System.DivideByZeroException
                'The catch block where  Exception will be handle
                'Here I am using e.Message
                MessageBox.Show(e.Message)
            End Try
        End Sub
    End Class
End Namespace
Figure 2: If I use e.Message.
If I write catch block like this:
Catch e As System.DivideByZeroException
          'The catch block where  Exception will be handle
          'Here I am using e.StackTrace
          MessageBox.Show(e.StackTrace)
End Try
 
Figure 3: If I use e.StackTrace.
If I write catch block like this:
Catch e As System.DivideByZeroException
          'The catch block where  Exception will be handle
          'Here I am using e.Source
          MessageBox.Show(e.Source)
End Try
Figure 4: If I use e.Source.
If I use finally in the .vb code like this:
Try
      'The try block from where an exception will thrown
      Result = a / b
      textBox3.Text = Result.ToString()
Catch e As System.DivideByZeroException
      'The catch block where  Exception will be handle
      'Here I am using e.Source
      MessageBox.Show(e.Source)
Finally
      MessageBox.Show("Hi In Finally block")
End Try
Here either there is exception in try block or not but finally block will execute surely.
Figure 5:
Throw Statement
By using throw we can throw an exception from any where in program.
Try
      'The try block from where an exception will thrown
      If a < 10 Then
            ' Form here an exception will be thrown If user enter number less then 10
            Throw New ArgumentOutOfRangeException(" First Number can't be less then 10")
      End If
      Result = a / b
      textBox3.Text = Result.ToString()
Catch e As Exception
      'The catch block where  Exception will be handle
      'Here I am using e.Message
      MessageBox.Show(e.Message)
End Try
If the user enters first number less then 10 then it throw an exception.
Figure 6:
Creating Our Own Exception Classes
To create our own exception class, the .NET framework requires us to drive our class from the Syatem.Exception class and recommends that we implement all the constructors that are implemented by the base class. Here are some important recommendations:
  • Give a meaning name to your Exception class and end it with Exception.
  • Do not develop a new Exception class unless there is a scenario for developers needing the class.
  • Throw the most specific exception possible.
  • Give meaningful message.
  • Do use InnerExceptions.
  • When wrong arguments are passed, throw an Argument Exception or a subclass of it, if necessary.
Let see this in a console base application.
Module Module1

    Sub Main()

        Try
            Dim m As MyException
            m = New MyException("My Exception Occured")
            m.ExtarcterrorInfo = "MyException Exter error information"
            Throw m
        Catch e As MyException
            Console.WriteLine(String.Concat(e.StackTrace, e.Message))
            Console.WriteLine(e.ExtarcterrorInfo)
            Console.Read()

        End Try
    End Sub

    Public Class MyException
        Inherits Exception

        Public Sub New()
            MyBase.New()

        End Sub
        Public Sub New(ByVal message As String)
            MyBase.New(message)
  
        End Sub

         Public Sub New(ByVal message As StringByVal e As Exception)
            MyBase.New(message, e)

         End Sub
        Dim strExtracrInfo As String

        Public Property ExtarcterrorInfo() As String
            Get
                Return strExtracrInfo
            End Get
            Set(ByVal value As String)
                strExtracrInfo = value
            End Set
        End Property
    End Class
End Module

When user run the application:

No comments:

Post a Comment

If the contents is insufficient or if there any error, please write here....


Suggestion are welcome:

Popular Posts