---
title: "Error Handling in ASP.NET"  
description: "In this blog I will talk about Error handling in ASP.NET  Types of Error Handling in Asp.NET1. Code Level2. Page Level3. Application LevelApplication"  
author: "priyanka kushwaha"  
published: 2015-02-19  
updated: 2015-02-19  
canonical: https://www.mindstick.com/blog/777/error-handling-in-asp-dot-net  
category: ".net"  
tags: ["c#", "asp.net"]  
reading_time: 4 minutes  

---

# Error Handling in ASP.NET

In this blog I will talk about [Error handling](https://www.mindstick.com/forum/160168/error-handling-in-go) in ASP.NET

\

##### Types of Error Handling in Asp.NET

1. Code Level

2. Page Level

3. Application Level

##### Application Level error Handling

An exception in the application can be handled using the custom [error pages](https://answers.mindstick.com/qa/95430/how-can-i-remove-error-pages-and-empty-pages-from-my-website-so-that-they-should-not-be-visible-on-google-webmaster-being-an-seo).

Custom error pages are displayed depending on the ASP.NET [Http status](https://www.mindstick.com/forum/160304/importance-of-http-status-codes-in-responses-to-httppost-methods-requests-in-dot-net-core-api) code.

Use the customErrors section in web.config.

This section lets you specify the error page to which the user should be redirected to when an handled exception propagates in the application level. This section specifies error pages for both default error [as well as](https://www.mindstick.com/interview/2481/can-you-write-a-java-class-that-could-be-used-both-as-an-applet-as-well-as-an-application) Http [status code](https://www.mindstick.com/forum/159703/what-is-the-http-status-code-when-a-resource-is-not-found-how-to-handle-it) errors.

```
   <system.web>     <customErrors
mode="On"
defaultRedirect="ErrorPage.aspx">        <error
statusCode="404" redirect="ErrorPage.aspx"/>      </customErrors>
    </system.web>
```

A custom errors element has the following three modes available:

Off: Custom Error page are not display.

On: Custom Error page are displayed on both local and remote machines.

Remote only: Custom Error pages are displayed on the remote machine and an exception on the local machine.

You can trap errors that occur anywhere in [your application](https://www.mindstick.com/forum/34702/please-tell-me-what-is-cross-site-scripting-and-how-is-it-harmful-for-your-application) by adding code to the Application_Error handler in the [Global.asax](https://www.mindstick.com/interview/33579/what-are-those-event-handlers-that-can-be-in-the-global-asax-file) file.

```
        protected 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.html", true);            }         }
```

##### Page Level error handling:

A page-level handler returns the user to the page where the error occurred, but because instances of controls are not maintained there will no longer be anything on the page.To provide the error details to the user of the application, you must specifically write the error detail to the page.

```
protected void Page_Load(object sender, EventArgs e)        {            throw new InvalidOperationException("An InvalidOperationException " +    "occurred in the Page_Load handler on the ErrorPage.aspx page.");        }private void Page_Error(object sender, EventArgs e)        {            // Get last error from the server.            Exception exc = Server.GetLastError();             // Handle specific exception.            if (exc is InvalidOperationException)            {                // Pass the error on to the error page.                Server.Transfer("ErrorPage.html?handler=Page_Error%20-%20Trail.aspx",                    true);            }
```

##### Code Level error handling :

An exception is a problem that arises during the execution of a program. It provides a way to transfer control from one part of a program to another.

C# [exception handling](https://www.mindstick.com/articles/12240/introduction-of-exception-handling) is built upon three keywords: _try, catch and throw.

Throw : A program throws an exception when a program show up. This is done using a throw keyword.

Try : A try block identifies a block of a code for which particular exceptions will be activated. It’s followed by one or more catch blocks.

Catch : A program catches an exception with an exception handler at the place in a program where you want to handle the problem. This is done using a catch keyword.

Finally: The [finally block](https://www.mindstick.com/articles/12106/exception-handling-in-java-guidelines-on-the-use-of-finally-block) is used to execute a given set of statement. Whether an exception is thrown or not thrown.

```
protected void ErrorButton_Click(object sender, EventArgs e)        {            //Response.Redirect("Trial.aspx");            throw new InvalidOperationException();        }private void Page_Error(object sender, EventArgs e)        {            // Get last error from the server.            Exception exc = Server.GetLastError();             // Handle specific exception.            try            {                if (exc is InvalidOperationException)                {                    // Pass the error on to the error page.                    Server.Transfer("ErrorPage.html?handler=Page_Error%20-%20Trail.aspx",                        true);                }            }            catch (Exception ex)            {                            }finally            {                Server.Transfer("ErrorPage.html");            }         }
```

##### Example:

##### 1. Create a DefaultPage.aspx

```
<html<body>    <form id="form1" runat="server">     <asp:Label id="Message" style="Z-INDEX: 101; LEFT: 34px;                 POSITION: absolute; TOP: 46px" runat="server"></asp:Label>            <asp:Button id="ErrorButton" style="Z-INDEX: 102; LEFT: 269px;                 POSITION: absolute; TOP: 41px" runat="server"                Text="Generate Error" OnClick="ErrorButton_Click"></asp:Button>    </form></body></html>
```

2. Write code on DefaultPage.cs

```
namespace CustomErrorExample{    public partial class DefaultPage : System.Web.UI.Page    {        protected void Page_Load(object sender, EventArgs e)        {            Message.Text = "This sample page an error";         }          protected void ErrorButton_Click(object sender, EventArgs e)        {           Response.Redirect("Trial.aspx");        }}}
```

\
3. Create a Global.asax file

```
  protected 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.html", true);          }         }
```

4.Create a ErrorPage.Html file

```
<html xmlns="http://www.w3.org/1999/xhtml"><head>    <title></title></head><body style="color:white;background-color:blue">      ERROR PAGE </body></html>
```

\
4. Create a web.config

```
<configuration>    <system.web>      <compilation debug="true" targetFramework="4.5" />      <httpRuntime targetFramework="4.5" />      <customErrors mode="On" defaultRedirect="ErrorPage.html">        <error statusCode="404" redirect="ErrorPage.html"/>       </customErrors>    </system.web></configuration>
```

![Error Handling in ASP.NET](https://www.mindstick.com/blogs/6de893b0-301d-4528-8772-3461be355232/images/0c4e2433-3fea-4828-a100-50a23d842a06.png)

![Error Handling in ASP.NET](https://www.mindstick.com/blogs/6de893b0-301d-4528-8772-3461be355232/images/bfe9f666-1ce0-46d1-b5c9-4c7894be47bc.png)

---

Original Source: https://www.mindstick.com/blog/777/error-handling-in-asp-dot-net

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
