Powered by Blogger.

Saturday, March 8, 2014

Exception handling in C#.Net




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.

Also you can check out:

- Simple JavaScript textbox validation example in Asp.Net

- Tutorial on WPF Controls and Layout

- Working with enterprise library for data access in asp.net Part-3

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