Exception Handling Techniques in ASP.NET

Introduction

Exceptions or errors are unusual occurrences that happen within the logic of an application. You cannot program for every possibility; hence, they are imminent. If an exception occurs within an application, the user is presented with a yellow page that looks ugly. So, how do you deal with these situations? You use exception handling techniques in ASP.NET.

Background

There are three ways to handle exceptions/errors in ASP.NET:

  1. try-catch block. This is also called Structured Exception Handling (SEH).
  2. Error Events.
  3. Custom Error Page.

You will look at each one of them in detail in the next sections.

try-catch Block

Enclose code that accesses files, databases, and so forth inside a try-catch block because access to those resources might be denied due to various reasons causing an exception. The third part of this block is finally. It is executed irrespective of the fact that an exception has been raised. Hence, use the finally block to complete the housekeeping jobs.

As a good programming practice, always catch specific exceptions. To view the exception types supported by the .NET Framework, use the Debug menu and select Exceptions in Visual Studio.NET.

In the following code, you try to access a table that does not exist in the Northwind database; therefore, an exception is raised. By using the try catch and finally block, you handle the exception and display a message.

try
{
   con = new SqlConnection("integrated security=SSPI;
      data source= (local);persist security info=False;
      initial catalog=Northwind");
   da = new SqlDataAdapter("Select * from TblNotExisits", con);
   ds = new DataSet();
   da.Fill(ds);
}
catch(SqlException ex)
{
   return "Connection Unsuccessful " + ex.Message;
}
finally
{
   con.Dispose();
}
return "Connection Successful";

Using Error Events

There are three different error events in ASP.NET that can be used in conjunction with SEH so that all exceptions are handled and the user is presented with a user-friendly error message.

  1. Page_Error: Occurs when an error occurs within the Web page. This event is in the Web form.
  2. Global_Error: Occurs when an error occurs within the application. This event is in the Gloabl.asax file.
  3. Application_Error: Occurs when an error occurs within the application. This event is in the Gloabl.asax file.

Methods in the Server object are used to handle the exception in the error events.

  1. GetLastError: Gets the last exception that occurred on the server.
  2. ClearError: Use this method to handle the exception and stop the error to trigger the subsequent error event or display the error to the user.

In the following code, you handle the exception in all the above three mentioned events but call the ClearError method only in the Application_Error event so that the error is propogated to the above level.

private void Page_Error(object sender, System.EventArgs e)
{
   Exception ex = Server.GetLastError();
   Response.Write("Handled error from Page<br>");
   //Server.ClearError();
}
protected void Application_Error(Object sender, EventArgs e)
{
   Exception ex = Server.GetLastError();
   Response.Write("Handled error from Application <br>");
   Server.ClearError();
}
protected void Global_Error(Object sender, EventArgs e)
{
   Exception ex = Server.GetLastError(); 
   Response.Write("Handled error from Global <br>"); 
}

Using Custom Error Pages

Use custom error page to handle HTTP exceptions such as page not found, unauthorized access, and so forth. You can specify custom error pages in two places:

  1. customErrors section of the web.config file. This setting specifies the application-wide error page to display for unhandled HTTP errors. HTTP errors are identified by the HTTP status code. Include the <error> tag in the customErrors to display a status code-specific error page. Does not work with .htm or .html files. Set the mode attribute to "On" to view the error page locally.
  2. errorPage attribute of the @Page directive of the Web form to display the error page for the error generated on the particular Web form.

The customsError section in the web.config file specifies the application to redirect to Error404.aspx file if a non-existent file is requested.

<customErrors mode="On" defaultRedirect="Error.aspx">
   <error statusCode="404" redirect="Error404.aspx" />
</customErrors>

The @Page directive specifies the error page to be redirected to if an error occurs in the Web page.

<%@ Page language="c#" Codebehind="PageErr.aspx.cs"
         AutoEventWireup="false"
         Inherits="ExceptionHandling.PageErr"
         errorPage="Error.aspx" %>


About the Author

Rohit Kukreti

He has been in Software field for last 11+ years. Always been programming on Microsoft technologies. He started with VB, ASP and then gradually moved on to ASP.Net. C# is the preferred language for development. When not working on some piece of code he likes to play table tennis and football. He is a huge fan of English Football club Manchester United.

Downloads

Comments

  • An excellent method for shoes that you simply could discover more about immediately.

    Posted by BobHotgloff on 05/22/2013 05:00am

    The Best Tips On How To Educate yourself about shoes And Ways In Which One Could Become a part of The sneakers Elite [url=http://www.shoesja.biz/]ベルーナ[/url] Resources and development throughout Nevada - - shoes actually leaves with no goodbye [url=http://www.shoesja.biz/adidas-アディダス-c-64.html]アディダス[/url] The main shoes Business Meaning : People who likes next to nothing is winning? [url=http://www.shoesja.biz/new-balance-ニューバランス-c-21.html]ニューバランス キッズ[/url] Hot queries about shoes answered in addition to reasons why you ought to check out every single term of this specific post. [url=http://www.shoesja.biz/nike-ナイキ-c-44.html]ナイキ[/url] A way to master every single thing there is to find out relating to sneakers in Three easy steps. [url=http://www.kutuja.com/]靴 通販[/url] The easiest way to comprehend every aspect there is to learn related to shoes in seven basic steps. [url=http://www.kutuja.com/adidas【アディダス】-c-1.html]アディダス[/url] All new questions regarding shoes clarified and reasons why you will need browse through each phrase of this specific guide. [url=http://www.kutuja.com/new-balance【ニューバランス】-c-206.html]ニューバランス キッズ[/url] The greatest formula for the shoes that you may discover more about right away. [url=http://www.kutuja.com/nike【ナイキ】-c-215.html]ナイキ[/url] A powerful solid double strain on shoes [url=http://www.shoesjp.biz/]アシックス[/url] The Trick For shoes [url=http://www.shoesjp.biz/adidas【アディダス】-c-640.html]adidas[/url] A double strain on shoes

    Reply
  • Things all the others has been doing in regards to nike and something that youought to do different.

    Posted by icoppyapedcap on 04/21/2013 10:19pm

    Mb [url=http://hunter-rain-boots.webnode.jp]ハンターレインブーツ[/url] cRy [url=http://hunterrainbootsjp.webnode.jp]ハンターレインブーツ[/url] u UyhQmh ZfcQ [url=http://hunter-boots8.webnode.jp]ハンターレインブーツ[/url] ag Y [url=http://rain-boots-men.webnode.jp]ハンター長靴[/url] mt [url=http://hunter-rain-boots-ja.webnode.jp]レインブーツメンズ[/url] VpuUgyTzv Z[url=http://rainshoesja.webnode.jp]ブーツ[/url] bmVtlFpxDj [url=http://ja-hunter-rain-boots.webnode.jp]レインブーツハンター[/url] m HtlXdm [url=http://rain-boots-popular.webnode.jp]レインシューズ[/url] Icy [url=http://rain-boots-men6.webnode.jp]hunter レインブーツ[/url] Vci Miy [url=http://jahunterrainboots.webnode.jp]ハンター長靴[/url] Lgl

    Reply
  • Those things that all the others does concerning nike and the things you will want to try and do totally different.

    Posted by icoppyapedcap on 04/21/2013 10:53am

    Fv [url=http://hunter-rain-boots.webnode.jp]レインブーツハンター[/url] hTc [url=http://hunterrainbootsjp.webnode.jp]レインブーツメンズ[/url] v CycJnw UlbP [url=http://hunter-boots8.webnode.jp]レインブーツメンズ[/url] gv O [url=http://rain-boots-men.webnode.jp]ハンター長靴[/url] cy [url=http://hunter-rain-boots-ja.webnode.jp]レインブーツメンズ[/url] ZzqIxbGhc Q[url=http://rainshoesja.webnode.jp]ブーツ[/url] crEmmAapNe [url=http://ja-hunter-rain-boots.webnode.jp]レインブーツハンター[/url] v MwjNba [url=http://rain-boots-popular.webnode.jp]レインブーツメンズ[/url] Ame [url=http://rain-boots-men6.webnode.jp]レインブーツハンター[/url] Sxx Zth [url=http://jahunterrainboots.webnode.jp]レインブーツメンズ[/url] Ggk

    Reply
  • Write Error Log or Exception Log into File in C# .NET

    Posted by Rashed on 03/19/2013 10:49pm

    Generally we are not interested to show any type of application error to end user. Error logs are very important for collecting all error data generated by an application. It is more useful during an early or beta release of a product. That's why it is better to store any kind of exceptions in one place. A good example about exception handling is : http://cybarlab.blogspot.com/2013/03/write-error-log-into-file-in-c-sharp.html

    Reply
  • Error Event Handling

    Posted by ShaunnyBwoy on 09/01/2008 07:01am

    I noticed that whilst you have supported the error response in the global.asax file, ASP would still overthrow the buffer and display the exception. For each of the event handlers to display the response desired, you would need to end the buffer with Response.End() to prevent ASP from overwriting the contents.

    Reply
Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • Where the business performance of their mobile app portfolios are concerned, most companies are flying blind. While traditional application portfolios are held to all kinds of ROI measure, the investment plan for mobile apps -- increasingly the more crucial bet -- is made by guesswork and dart-throwing. This interactive e-book investigates how mobile is driving the need for app and portfolio measures unlike any we saw in the days of web. Good mobile analytics must deliver leading indicators of user experience …

  • Live Event Date: August 13, 2014 @ 1:00 p.m. ET / 10:00 a.m. PT If you are developing applications, you'll want to join us to learn how applications are changing as a result of gesture recognition. This technology will change how you and your users interact - not simply with your devices, but with the world around you. Your devices will be able to see and hear what your users are doing. Are your applications ready for this? Join us to learn about Intel® RealSense™ Technology, including never been …

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds