Wednesday, October 03, 2007

Error Handling in .Net with Example

Error Handling in .Net with Easy Example and Step by Step guide.

What is Exception?
An exception is unexpected error or problem.

What is Exception Handling?
Method to handle error and solution to recover from it, so that program works smoothly.

What is try Block?

  • try Block consist of code that might generate error.
  • try Block must be associated with one or more catch block or by finally block.
  • try Block need not necessarily have a catch Block associated with it but in that case it must have a finally Block associate with it.
Example of try Block

Format1
try
{
//Code that might generate error
}
catch(Exception errror)
{
}

Format2
try
{
//Code that might generate error
}
catch(ExceptionA errror)
{
}
catch(ExceptionB error)
{
}

Format3
try
{
//Code that might generate error
}
finally
{
}


What is catch Block?
  • catch Block is used to recover from error generated in try Block.
  • In case of multiple catch Block, only the first matching catch Block is executed.
  • when you write multiple catch block you need to arrange them from specific exception type to more generic type.
  • When no matching catch block are able to handle exception, the default behavior of web page is to terminate the processing of the web page.
Example of catch Block

Format1
try
{
//Code that might generate error
}
catch(Exception errror)
{
//Code that handle errors occurred in try block
}


Format2
try
{
//Code that might generate error
}
catch(DivideByZeroException errror)
{
//Code that handle errors occurred in try block
//Note: It is most specific error we are trying to catch
}
catch(Exception errror)
{
//Code that handle errors occurred in try block
//Note: It is not specific error in hierarchy
}
catch
{
//Code that handle errors occurred in try block
//Note: It is least specific error in hierarchy
}


Explain finally Block?
  • finally Block contains the code that always executes, whether or not any exception occurs.
  • When to use finally Block? - You should use finally block to write cleanup code. i.e. you can write code to close files, database connections, etc.
  • Only One finally block is associated with try block.
  • finally block must appear after all the catch block.
  • If there is a transfer control statement such as goto, break or continue in either try or catch block the transfer happens only after the code in the finally block is executed.
  • If you use transfer control statement in finally block, you will receive compile time error.
Example of finally Block

Format1
try
{
//Code that might generate error
}
catch(Exception errror)
{
//Code that handles error and have solution to recover from it.
}
finally
{
//Code to dispose all allocated resources.
}

Format2
try
{
//Code that might generate error
}
finally
{
//Code to dispose all allocated resources.
}


Explain throw statement?
  • A throw statement is used to generate exception explicitly.
  • Avoid using throw statement as it degrades the speed.
  • throw statement is generally used in recording error in event log or sending an email notification about the error.
Example of throw statement
try
{
//Code that might generate error
}
catch(Exception errror)
{
//Code that handles error and have solution to recover from it.

throw; //Rethrow of exception to Add exception details in event log or sending email.
}


Explain using statement?
  • using statement is used similar to finally block i.e. to dispose the object.
  • using statement declares that you are using a disposable object for a short period of time. As soon as the using block ends, the CLR release the corresponding object immediately by calling its dispose() method.
Example of using statement in C#

//Write code to allocate some resource
//List the allocated resource in a comma-seperated list inside
//the parantheses of the using block

using(...)
{
//use the allocated resource.
}

//here dispose method is called for all the object referenced without writing any additional code.


Is it a best practice to handle every error?
No, it is not best practice to handle every error. It degrades the performance.
You should use Error Handling in any of following situation otherwise try to avoid it.
  • If you can able to recover error in the catch block
  • To write clean-up code that must execute even if an exception occur
  • To record the exception in event log or sending email.

Difference between catch(Exception ex) and catch
try
{
}
catch(Exception ex)
{
//Catches all cls-compliant exceptions
}
catch
{
//Catches all other exception including the non-cls compliant exceptions.
}


Managing Unhandled Exception You can manage unhandled exception with custom error pages in asp.net. You should configure the <customErrors> element in web.config file. It has two attributes:
  • Mode Attribute: It specifies how custom error page should be displayed. It contains 3 values.
    • On - Displays custom error pages at both the local and remote client.
    • Off - Disables custom error pages at both the local and remote client.
    • RemoteOnly - Displays custom error pages only at the remote client, for local machine it displays default asp.net error page. This is default setting in web.config file.
  • defaultRedirect: It is an optional attribute to specify the custom error page to be displayed when an error occurs.
  • You can display custom error page based on http error statusCode using error element inside the customeError element, in case the no specific statusCode match it will redirect to defaultRedirect page.
  • <customErrors mode="RemoteOnly" defaultRedirect="~/DefaultErrorPage.htm">
    <error statusCode="403" redirect="NoAccess.htm" />
    <error statusCode="404" redirect="FileNotFound.htm" />
    </customErrors>
Example of Unhandled Exception
I have created a sample website which can generate unhandled exception, divide by zero.



This will result into default error page generated by asp.net



To suppress error with CustomError Page you need to define customError element in Web.Config file.

Example:
<customErrors mode="On" defaultRedirect="~/DefaultErrorPage.htm">
</customErrors>

This setting web.config will display default error page whenever web application generates unhandled exception

Now, after adding the above code in web.config file and creating a sample DefaultErrorPage.htm in root directory it will redirect to DefaultErrorPage.htm whenever unhandled exception occurs.



Similarly you can display error message for different http status code

<customErrors mode="On" defaultRedirect="~/DefaultErrorPage.htm">
<error statusCode="403" redirect="~/HttpError.aspx?ErrorCode=403" />
<error statusCode="404" redirect="~/HttpError.aspx?ErrorCode=404" />
</customErrors>

Here we are using HttpError.aspx page to display all http errors by passing the error code as querystring.

You need to place following code into HttpError.aspx page to make this work

protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
string sErrorCode = Request.QueryString["ErrorCode"].ToString();
switch (sErrorCode)
{
case "403": Label1.Text = "Error: Request Forbidden";
break;
case "404": Label1.Text = "Error: Page Not Found";
break;
}
}
}

So lets click on page which is not present in web application and can generate page not found error.








Events fired on Unhandled Exception
Two events fire in successive order on unhandled exception
  • Page.Error() Event - Performing error handling at page level.
  • Application.Error() Event - Performing error handling at application level.

Page.Error() Event
Let display error message in above divide by error instead of display custom error page.

Add the Page_Error() Event

protected void Page_Error(object sender, EventArgs e)
{
Response.Write("Error: " + Server.GetLastError().Message + "");
Server.ClearError();
}

Server.GetLastError() method is used to display last error, while Server.ClearError() will clear the last exception and does not fire the subsequent error events. For this reason, you will notice that custom error page is not displayed even though there is unhandled error, and a default error message is displayed.






Application.Error() Event
Application.Error Event is used to handle unhandled exception of entire application. This event lies in Global.asax file. You can use this event to send email for error or generate a text file or recording error information in database, etc.

Here we will generate a text file in MyError directory of application and send email of same error to web master.

So lets begin by adding namespace to global.asax

For adding namespace to global.asax make use of import statement.

<%@ Import Namespace="System.IO" %>
<%@ Import Namespace="System.Net" %>
<%@ Import Namespace="System.Net.Mail" %>


Now, add following code to Application_Error Event in Global.asax for generating error text file and sending error reporting email to webmaster in asp.net

void Application_Error(object sender, EventArgs e)
{
Exception err = (Exception)Server.GetLastError().InnerException;

//Create a text file containing error details
string strFileName = "Err_dt_" + DateTime.Now.Month + "_" + DateTime.Now.Day
+ "_" + DateTime.Now.Year + "_Time_" + DateTime.Now.Hour + "_" +
DateTime.Now.Minute + "_" + DateTime.Now.Second + "_"
+ DateTime.Now.Millisecond + ".txt";

strFileName = Server.MapPath("~") + "\\MyError\\" + strFileName;
FileStream fsOut = File.Create(strFileName);
StreamWriter sw = new StreamWriter(fsOut);

//Log the error details
string errorText = "Error Message: " + err.Message + sw.NewLine;
errorText = errorText + "Stack Trace: " + err.StackTrace + sw.NewLine;
sw.WriteLine(errorText);
sw.Flush();
sw.Close();
fsOut.Close();

//Send an Email to Web Master
//Create Mail Message Object with content that you want to send with mail.
MailMessage MyMailMessage = new MailMessage("dotnetguts@gmail.com","vivek_on_chat@yahoo.com",
"Exception:" + err.Message, errorText);

MyMailMessage.IsBodyHtml = false;

//Proper Authentication Details need to be passed when sending email from gmail
NetworkCredential mailAuthentication = new
NetworkCredential("dotnetguts@gmail.com", "password");

//Smtp Mail server of Gmail is "smpt.gmail.com" and it uses port no. 587
//For different server like yahoo this details changes and you can
//get it from respective server.
SmtpClient mailClient = new SmtpClient("smtp.gmail.com",587);

//Enable SSL
mailClient.EnableSsl = true;
mailClient.UseDefaultCredentials = false;
mailClient.Credentials = mailAuthentication;
mailClient.Send(MyMailMessage);
}

On running the program and generating exception will create error file in MyError directory and will send email stating error to web master, And it will display custom error page to user.


Error Text File generated on unhandled exception.



Email is sended to web master, with subject as Error Message.




Error description is stated as below.

12 comments:

Rajni said...

Good Error Handling article, It helped me, Thanks.

Anonymous said...

Excellent and comprehensive article. Many thanks.

Anonymous said...

A really simple concise article. Many Thanks.

INNA MARY SWAPNA said...

Hi,
The article is very nice and understandble.If u give the article about the Expetionhandler in Application also very nice

sahil31_mohali said...

great

ASP Dot Net Developer said...

Greet Learning Article

Fresher said...

Great Article ,Thanks for posting!!!

Plz post more such articles .It will be very helpfull for freshers like me!!!

srinivas said...

great expalantion..Thank you for posting..

Richard Baby Varghese said...

good one, Thanks for sharing
Richard Varghese

Pradeep Kumar Yadav said...

Very Good expalantion..Thanks alot for your posting..

Satya Phani said...

Nice article... got rid of confusion on exception handling... Thanks a lot

krishna prasad Reddy said...

good article..
it is using 2 cache the concept..thanks alot man...

Most Recent Post

Community Updates

Subscribe Blog via Email

Enter your email address:



Disclaimers:We have tried hard to provide accurate information, as a user, you agree that you bear sole responsibility for your own decisions to use any programs, documents, source code, tips, articles or any other information provided on this Blog.
Page copy protected against web site content infringement by Copyscape