Exception Class in C#.Net


Here we will discuss exception class in C#.Net. Also, you can check out my previous posts on:
It is always good to do exception and error handling in Asp.Net or C#.Net code. Because it is not a good idea to show exception message rather we should catch the proper exception and show proper messages to users. .The 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 the 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.
Check out Best Alternative to InfoPath -> Try Now

You May Also like the Following SharePoint Online Tutorials:

About Bijay Kumar

I am Bijay from Odisha, India. Currently working in my own venture TSInfo Technologies in Bangalore, India. I am Microsoft Office Servers and Services (SharePoint) MVP (5 times). I works in SharePoint 2016/2013/2010, SharePoint Online Office 365 etc. Check out My MVP Profile.. I also run popular SharePoint web site SharePointSky.com

View all posts by Bijay Kumar →