Exception handling in ASP.NET
In this article we are going to see various ways in which we can handle exceptions in ASP.NET
In Web Applications, There are basically four ways of handling the Exceptions.
a. Using Try,Catch Block.
b. Using Page_Error event.
c. Using Application_Error event of Global.asax file.
d. Using Custom Errors in web.config file.
1. Exception handling using Try/Catch block :
Basically we use Try/Catch blocks around any code that we suspect may throw errors. Example below takes the numerator and denominator values from the values entered by the user in textbox and performs division. Since the division logic is enclosed in try catch block, if the denominator is 0 the division operation results in Attempted to divide by zero exception and the execution is transferred to catch block where we are handling the exception and displaying the corresponding exception message to the user.
The following code demonstrates this:
decimal num1 = Decimal.Parse(txtNum1.Text);
decimal num2 = Decimal.Parse(txtNum2.Text);
decimal result = num1 / num2;
catch (Exception ex)
If possible, you should handle errors in Try/Catch blocks within your code, because a problem is more easily corrected where it occurs. As in the above example, user can understand what the problem is and can correct the problem and the page needs to return to the same place.
2. Page Level Exception Handler:
When an error occurs in a page if it is not handled in the Try/Catch block. we can handle it in Page_Error event of the page. If a Page-level handler handles the error, it returns you to the page, but there is no longer anything on the page because instances of controls are not created. To provide the user any information, you must specifically write it to the page.
You can use a page-level error handler :
1. To log unhandled errors.
2. To take the user to a page that can display helpful information.
This code example shows a handler for the Page_Error event in an ASP.NET Web page. This handler catches the exceptions that are not already handled within Try/Catch blocks in the page.
protected void Page_Error(object sender, EventArgs e)
Server.Transfer("~/ErrorHandler.aspx");//Whenever an error occurs in this webpage and if it is not handled in try/catch block. User is redirected to ErrorHandler.aspx page.
3. Handling errors in Global.asax file :
All the errors that are not caught with in a Try/Catch block or in a page-level error handler can be caught in Application_Error event handler of the Global.asax file.
This code example shows how to create an error handler in the Global.asax file that will catch all unhandled ASP.NET errors while processing a request. The Application_Error event handler in Global.asax will process all unhandled errors.
If the Global.asax file is not added to your Website. Go to View Menu ->Select Solution Explorer ->Right Click on the Project ->Select Add New Item -> Under Templates select Global Application Class (Name: Global.asax) ->click on Add. This will add and open Global.asax file in Visual Studio.
The following example provides the ErrorLogUtility file. All the errors which might occur in a Web Application are written to the ErrorLog file. You can also immediately notify system/site administrators of a problem that occurs in a web Application. The following ErrorLogUtility has a static method to log the exception. How this method is implemented in your code depends on the needs of the organization. For this example, you must grant write permissions to the NETWORK SERVICE /ASPNET account for the App_Data folder to enable the application to write to the error log file present in App_Data folder of you application.
In the App_Code folder of your Application. Add a class ErrorLogUtility. Right click on App_Data folder and add a Text File (Name: ErrorLog.txt) to the website.
public class ErrorLogUtility
// TODO: Add constructor logic here
// Log an Exception
public static void LogError(Exception exc)
// Include the logic for logging exceptions
// Get the absolute path to the log file
string logFile = "App_Data/ErrorLog.txt";
logFile = HttpContext.Current.Server.MapPath(logFile);
// Open the log file for append and write the log
StreamWriter sw = new StreamWriter(logFile, true);
sw.Write("----------------------- " + DateTime.Now);
if (exc.InnerException != null)
sw.Write("Inner Exception: ");
if (exc.InnerException.StackTrace != null)
sw.WriteLine("Inner Stack Trace: ");
sw.WriteLine("Exception: " + exc.Message);
sw.WriteLine("Stack Trace: ");
if (exc.StackTrace != null)
The following code should be written in the Global.asax file to handle the error and log the error.
void Application_Error(object sender, EventArgs e)
// Code that runs when an unhandled error occurs
// Give the user error information and log it.
Exception ex = Server.GetLastError();
Response.Write("Global Page Error\n");
Response.Write(" +ex.Message + "\n");
if (ex.InnerException != null)
Response.Write("Error " +ex.InnerException.Message + "");
// Log the exception and notify system operators
// Clear the error from the server
4. Handling the Errors using web.config file:
Uncomment the CustomErrors section found under Authentication section in web.config file. Add three files GenericErrorPage.htm, NoAccess.htm, FileNotFound.htm to your website with error details describing the error.
The section enables configuration of what to do when an unhandled error occurs during the execution of a request. We can configure either html or aspx error pages to be displayed in place of a error stack trace. If the error occurs in your application and the Error Status code is 403 then the user is redirected to NoAccess.htm page similarly if the Error Status code is 404 then the user is redirected to FileNotFound.htm page. You can write any number of error sections under customErrors depending on the requirement. If the error statusCode is neither 403 nor 404 then the user is redirected to GenericErrorPage.htm as specified in the defaultRedirect attribute of customErrors section. When the user is redirected to customErrorPage like NoAccess.htm, the querystringparameter "aspxerrorpath" is appended to the url of the page which actually has the error.
The mode attribute of customErrors section takes any of the following values:
1. RemoteOnly : This configures the application to show detailed errors only to local users (Developer). If the request is from a Remote user, Redirect the user to Custom error page.
2. Off : Both Local and Remote users , It shows detailed errors and does not redirect to custom Error page.
3. On: Both Local and Remote users are redirected to the Error Page.
1. It is better to use Try/Catch blocks around any code that is subject to errors instead of relying on a global error handler.
2. Never set customErrors to Off in your Web.config file if you do not have an Application_Error handler in your Global.asax file. Potentially compromising information about your Web site can be exposed to anyone who can cause an error to occur on your site.
3. An error handler that is defined in the Global.asax file will only catch errors that occur during processing of requests by the ASP.NET runtime. For non-ASP.NET errors, you can create a custom handler in Internet Information Services (IIS). The custom handler will also not be called for server-level errors.
4. You cannot directly output error information for requests from the Global.asax file; you must transfer control to another page, typically a Web Forms page. When transferring control to another page, use Transfer method. This preserves the current context so that you can get error information from the GetLastError method.
5. After handling an error, you must clear it by calling the ClearError method of the Server object (HttpServerUtility class).
6. Include error handling whenever practical and construct your own error messages. In your error handler, you can test to see whether the user is local and react accordingly.
7. Create a global error handler at the page or application level that catches all unhandled exceptions and routes them to a generic error page. That way, even if you did not anticipate a problem, at least users will not see an exception page.
Note: Always Global.asax file settings will take precedence over the web.config file CustomErrors settings.
1. Every Web Application can contain only one Global.asax file and it must be present in the root directory.
2. When the Web application is started, ASP.NET creates an instance of the Global.asax class that is derived from HttpApplication class and this class is used to represent the application.
Exception: Errors in the program at run time are called exceptions.
Context: Provides access to the entire current context such as user session,Current Http Request. You can use this class to share information between pages.
Custom Errors: Provides information about custom error messages for an ASP.NET application.
Network Service/ASPNET account: By default, ASP.NET pages run with the Windows identity of the service that processes ASP.NET pages on the Web server. On a computer running Windows Server 2003, that identity is by default, the NETWORK SERVICE account. On computers running Windows 2000 and Windows XP Professional, the identity is the local ASPNET account which is created when the .NET Framework is installed.
MapPath: It returns the Physical path that corresponds to the specified virtual path on the Web Server.
InnerException: Gets the Reference to actual Exception raised in the page that caused the current Exception.