Search - Articles
DevASP.NET for ASP.NET, VB.NET, XML and C# (C-Sharp) Developers Tuesday, March 03, 2009
Dev Articles
Search Directory
SQL Server

How exception handling is done in VB.Net and how to create custom exception.

Author: Shahzad

This article gives you a little idea about exception handling in Visual Basic.Net and also how you can create your own custom exceptions and then throw them later.

Exception handling is an important issue in application development. In VB.Net we can handle exceptions with great ease and we can also create our own customized exceptions which can later be used for our applications specific needs.


During the execution of an application certain errors may occur. If a developer knows exactly where the error is going to occur and what is the thing which is about to cause this error then he can deal with it very gracefully in the code. For example, if you know that a variable must have a value greater than zero otherwise it’ll cause some error then you can simply check the value of this variable and can take some appropriate action, like you can exit your sub routine etc. However, under certain circumstances you are not fully aware when the error will occur and what will be the cause of this error. In such situation the Try…Catch mechanism comes to rescue


You can enclose the code, which is suspicious, in Try …Catch block and can display the error message shown by the exception type of object.  Here, you can handle the exceptions in two different ways.


First, you can catch a generic exception as given below




   ‘Suspicious code goes here


Catch Ex as Exception


    MessageBox.Show(“Error : “ & Ex.ToString)


End Try


Second, you can catch a specific exception by with the help of specific exception class as given below




   ‘Suspicious code goes here


Catch Ex as OverflowException


 ‘It will catch exceptions only when an overflow occurs


   MessageBox.Show(“Error : “ & Ex.ToString)


End Try


You can also define your own custom exception class and then throw that kind of exception.


For example,


Public Class MyException Inherits System.Exception


Sub New(ByVal ErrMsg As String)


End Sub



End Class


Now you can throw and catch exception of “MyException” type.




        ‘Some code goes here


        Throw(New MyException(“MyException kind of Exception”)


Catch  Ex as MyException


       MessageBox.Show(“Error : “ & Ex.ToString)


End Try

Now the above code throws an exception of type “MyException” and Catch block catches the exception only when it is of type “MyException”

Add Article Comment:
Name :
Email Address :
Comments :
<< Create SQL Server database and table using Visual Basic.Net.

Disclaimer - Privacy
© 2002-2017