Thursday 20 September 2012

Error Handling in .Net

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

"EXCEPTION IS A RUNTIME ERROR WHICH ARISES BECAUSE OF ABNORMAL CONDITION IN A CODE SEQUENCE. "

Exception handling uses the try, catch, and finally keywords to attempt actions that may not succeed, to handle failures, and to clean up resources afterwards.Exceptions can be generated by the common language runtime (CLR), by third-party libraries, or by the application code using the throw keyword.

When your application encounters an exceptional circumstance, such as a division by zero or low memory warning, an exception is generated. If no exception handler for a given exception is present, the program stops executing with an error message. If a catch block defines an exception variable, you can use it to get more information on the type of exception that occurred.

Exception objects contain detailed information about the error, including the state of the call stack and a text description of the error.


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

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

    Try/catch/finally block
    Using Error Events 
    Using Custom Error Page


1. Try/catch/finally block

try Block
try Block consist of code that might generate error and it's must be associated with one or more catch block or by finally block. It's 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

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

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

Example 3
try
{
//Code that might generate error
}
finally
{
}


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

Example 1



Example 2




















finally Block
The finally block is useful for cleaning up any resources that are allocated in the try block, and for running any code that must execute even if an exception occurs in the try block.

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 you use transfer control statement in finally block, you will receive compile time error.

Example of finally Block

Example 1
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.
}

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



What is throw statement?
The throw statement is used to signal the occurrence of an anomalous situation (exception) during the program execution.

Usually the throw statement is used with try-catch or try-finally statements. When an exception is thrown, the program looks for the catch statement that handles this exception.

throw exception;

You can also rethrow a caught exception using the throw statement

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
//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.


Best Practices for Handling Exceptions
When you are develop any type of .NET Application, the Exception handling is important for all to prevent unwanted crashing of applications. Exceptions are runtime errors which might be caused by some operation illegal to the application.

The following list contains suggestions on best practices for handling exceptions:

Know when to set up a try/catch block. For example, you can programmatically check for a condition that is likely to occur without using exception handling. In other situations, using exception handling to catch an error condition is appropriate.

The following example uses an if statement to check whether a connection is closed. You can use this method instead of throwing an exception if the connection is not closed.

















2. Error handling events 

• Page_Error: This is page event and is raised when any unhandled exception occur in the page.

• Application_Error: This is application event and is raised for all unhandled exceptions in the ASP.NET application and is implemented in global.asax


3. Using Custom error page
The <customErrors> section in web.config has two attributes that affect what error page is shown: defaultRedirect and mode. The defaultRedirect attribute is optional. If provided, it specifies the URL of the custom error page and indicates that the custom error page is shown instead of the Runtime Error. The mode attribute is required and accepts three values: On, Off, and RemoteOnly. These values have the following behavior:

<customErrors mode="On" defaultRedirect="/ErrorPages/AppError.html">
    <error statusCode="404" redirect="/ErrorPages/404.html" />
</customErrors>

On - indicates that the custom error page or the Runtime Error is shown to all visitors, regardless of whether they are local or remote.

Off - specifies that the Exception Detail is displayed to all visitors, regardless of whether they are local or remote.

RemoteOnly - indicates that the custom error page or the Runtime Error that is shown to remote visitors, while the Exception Detail is shown to local visitors.






2 comments:

  1. Mr.Gopalan Mani Sir,

    Can use Try catch block in function?

    ReplyDelete
  2. Hi Ramesh,
    You should place try-cacth block in the place where you can do something meaningful with caught exception. Like you log it or show it to the user

    ReplyDelete