Hello All, We are going to start new batch from next week. message/call or mail us for more details.

5 September 2013

Types Of Exception Handling Techniques in ASP.NET

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.


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.
  1. try
  2. {
  3. con = new SqlConnection("integrated security=SSPI;
  4. data source= (local);persist security info=False;
  5. initial catalog=Northwind");
  6. da = new SqlDataAdapter("Select * from TblNotExisits", con);
  7. ds = new DataSet();
  8. da.Fill(ds);
  9. }
  10. catch(SqlException ex)
  11. {
  12. return "Connection Unsuccessful " + ex.Message;
  13. }
  14. finally
  15. {
  16. con.Dispose();
  17. }
  18. 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.
  1. private void Page_Error(object sender, System.EventArgs e)
  2. {
  3. Exception ex = Server.GetLastError();
  4. Response.Write("Handled error from Page<br>");
  5. //Server.ClearError();
  6. }
  7. protected void Application_Error(Object sender, EventArgs e)
  8. {
  9. Exception ex = Server.GetLastError();
  10. Response.Write("Handled error from Application <br>");
  11. Server.ClearError();
  12. }
  13. protected void Global_Error(Object sender, EventArgs e)
  14. {
  15. Exception ex = Server.GetLastError();
  16. Response.Write("Handled error from Global <br>");
  17. }

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.
  1. <customErrors mode="On" defaultRedirect="Error.aspx">
  2. <error statusCode="404" redirect="Error404.aspx" />
  3. </customErrors>
The @Page directive specifies the error page to be redirected to if an error occurs in the Web page.
  1. <%@ Page language="c#" Codebehind="PageErr.aspx.cs"
  2. AutoEventWireup="false"
  3. Inherits="ExceptionHandling.PageErr"
  4. errorPage="Error.aspx" %>
 

3 comments: