SoFunction
Updated on 2025-03-03

Error handling Application_Error event example

The error handling method Application_Error event is as follows:

Create a new web program - Create a new page - Add the following code to this page:

Copy the codeThe code is as follows:

<SCRIPT language=C# runat="server">
void Page_Load(object sender, e)
{
throw(new ArgumentNullException());
}
</SCRIPT>

Then, add the Application_Error event to the file to catch the error raised in the Page_Load event of the page. Add the following code to the file:

Copy the codeThe code is as follows:

protected void Application_Error(object sender, EventArgs e)
{
Exception objErr = ().GetBaseException(); //Get the error
string err ="Error Caught in Application_Error event/n" +
"Error in:" + () +
"/nError Message:"+ () +
"/nStack Trace:"+ ();
//Write the captured errors into the application log of Windows, and you can access the application log from the event viewer.
("Test2", err, );
(); //Clear the exception, no longer catches this exception elsewhere.
}

Save the action you just did, in Visual Studio .NET, on the Build menu, click Build. Right-click the page and click View in browser. In this case the page will be blank, but you should notice that a new item has been added to the event log. This example generates an item in the application log that allows access to the application log from the event viewer. After logging an error, you may want to redirect the user to another user-friendly error page or perform some other actions as needed that can be done as you want.