Powered by Blogger.

Saturday, February 22, 2014

Exception Class in C#.Net



Here we will discuss about exception class in C#.Net. Also you can check out my previous posts on:

- Difference between web application and web site in Asp.Net

- How to display serial number automatically in GridView in asp.net?

- How to get distinct data from tables in sql server 2008?

It is always good to do exception and error handling in Asp.Net or C#.Net code. Because it is not good idea to show exception message rather we should catch the proper exception and show proper messages to users. .Net language supports structured exception handling. Whenever an error occurred .Net framework creates an exception object which we can use to do exception handling.

Microsoft .Net framework provides The Exception class known as System.Exception. This is the base class for all exceptions. Means every exception is derived from this base class. Some of the classes provided by DotNet framework are NullReferenceException, IOException, SqlException, DivideByZeroException, ArithmeticException, IOException, SecurityException etc.

The exception has some useful members/properties to know more about the error like InnerException, Message, StackTrace, Source etc. We can get these like below:

catch (System.Exception ex)
{
string errorMessage = ex.Message;
}

try
{
// Code
}
catch (System.Exception ex)
{
// Error catch block
}
finally
{
// Clean up block.
}

We can write the generic Exception class. But its is better to trap proper exception message. We can trap by using multiple catch block like below.

try
{
// Risky database code goes here.
}
catch (System.Data.SqlClient.SqlException ex)
{
string errorMessage = ex.Message;
// Catch SQL Exception
}
catch (System.NullReferenceException ex)
{
string errorMessage = ex.Message;
// Catches null reference exception.
}
catch (System.Exception ex)
{
string errorMessage = ex.Message;
// Error catch block
}

If the particular exception belongs to SqlException then it will go to the 1st exception block, else if it belongs to nullreference exception then it will go to the 2nd catch block else it will go to the 3rd catch block since it is the generic exception block.

You can also write nested try catch and exception code.



0 comments

Post a Comment