Sunday, August 4, 2013

What is exception handling? How to handle exceptions at page level as well as application level by writing code at one place only?

Discovering and handling the parts of a program that are most likely to produce errors at execution time is called exception handling. A well-designed set of error handling code blocks can make a program or software more robust and less inclined to crashing because the application handles such errors. An unhandled exception causes the abnormal termination of the program and may result in data loss.

.Net provides an elegant way to handle runtime errors with the help of the try, catch, and finally keywords to handle page level errors. Here is the sample code:

public class ExceptionHandlingExample
{  
   public void DoWork()
    {    
        // Do some work that might throw exceptions.
    }
    public void MethodWithHandler()
    {
        try
        {
            DoWork();
        }
        catch (Exception e)
        {          
              // Handle the exception and continue executing.
        }
    }
}

You can handle default errors at the application level by adding an Application_Error handler in the Global.asax file of your application and a customErrors section to the Web.config file. A generic custom error page for most runtime errors is highly recommended. The customErrors section allows you to specify a default page where users will be redirected to when an error occurs. Here is the code section you need to write or modify in your Web.config file:

<configuration>
  <system.web>
    <customErrors mode="On" defaultRedirect="ErrorPage.aspx?handler=customErrors%20section%20-%20Web.config">
      <error statusCode="404" redirect="ErrorPage.aspx?msg=404&amp;handler=customErrors%20section%20-%20Web.config"/>
    </customErrors>
  </system.web>
</configuration>

To get error details on custom error page, Write following code in Global.asax file:

void Application_Error(object sender, EventArgs e)
{    
    Exception exc = Server.GetLastError();
    if (exc is HttpUnhandledException)
    {   
       // Pass the error on to the error page.
        Server.Transfer("ErrorPage.aspx?handler=Application_Error%20-%20Global.asax", true);
    }

}

3 comments:

  1. I always emailed this weblog post page to all my associates, for the
    reason that if like to read it after that my contacts will too.


    Look into my web-site minecraft games

    ReplyDelete
  2. I blog quite often and I really appreciate your content.
    The article has truly peaked my interest. I will take a note
    of your blog and keep checking for new information about once per week.
    I opted in for your Feed too.

    Also visit my web page - MosheHJann

    ReplyDelete
  3. Paragraph writing is also a excitement, if you be familiar with after that you can write otherwise
    it is complex to write.

    Feel free to visit my page :: CatharineYLouthan

    ReplyDelete