SIGN UP MEMBER LOGIN:    
ARTICLE

Exception Handling in VB.Net

Posted by Mahesh Chand Articles | Exception Handling C# June 25, 2007
Exception handling is crucial since the robustness of software depends on how effectively a program deals with exceptions.
Reader Level:

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 Object, ByVal 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 String, ByVal 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:

Login to add your contents and source code to this article
share this article :
post comment
 
6 Months Free & No Setup Fees ASP.NET Hosting!
Become a Sponsor
PREMIUM SPONSORS
  • ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
    Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites - Click Here!
6 Months Free & No Setup Fees ASP.NET Hosting!
Become a Sponsor