Using Try Catch in Risky Situations

Learning Resources
 

Using Try Catch in Risky Situations


If possible, you should handle errors in Try/Catch blocks within your code, because a problem is more easily corrected where it occurs. If the user can help correct a problem, the page needs to return to the same place so the user has a context for understanding what to do.

A page-level handler 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 would probably use a page-level error handler to log unhandled errors or to take the user to a page that can display helpful information.

This code example shows a handler for the Error event in an ASP.NET Web page. This handler catches all exceptions that are not already handled within Try/Catch blocks in the page.

After you handle an error, you must clear it by calling the ClearError method of the Server object (HttpServerUtility class).

This handler filters for specific kinds of exceptions. For an ArgumentOutOfRangeException exception, the handler writes some text on the page, provides a link back to the page, logs the error, and notifies system administrators. For an InvalidOperationException exception, the handler simply transfers the exception to the Generic Error Page. For any other kind of exception, the handler does nothing, which allows your site to automatically redirect to the generic page specified in the Web.config file. Your own code would filter for exceptions that are important to your application.


The following example is part of a complete code sample in Complete Example for Error Handlers

private void Page_Error(object sender, EventArgs e)
{
  // Get last error from the server
  Exception exc = Server.GetLastError();

  // Handle exceptions generated by Button 1
  if (exc is InvalidOperationException)
  {
    // Pass the error on to the Generic Error page
    Server.Transfer("GenericErrorPage.aspx", true);
  }

  // Handle exceptions generated by Button 2
  else if (exc is ArgumentOutOfRangeException)
  {
    // Give the user some information, but
    // stay on the default page
    Response.Write("

Default Page Error

\n");
    Response.Write("

Provide as much information here as is " +
      "appropriate to show to the client.

\n");
    Response.Write("Return to the " +
        "Default Page
\n");

    // Log the exception and notify system operators
    ExceptionUtility.LogException(exc, "DefaultPage");
    ExceptionUtility.NotifySystemOps(exc);

    // Clear the error from the server
    Server.ClearError();
  }
  else
  {
    // Pass the error on to the default global handler
  }
}

 


To include error handling

    Use a try-catch block around any statements that might generate errors.

    Optionally, test for a local user with the IsLocal property and modify error handling accordingly. The value 127.0.0.1 is equivalent to localhost and indicates that the browser is on the same computer as the Web server.

    The following code example shows an error-handling block. If an error occurs, a session state variable is loaded with details about the message, and the application then displays a page that can read the Session variable and display the error. (The error is deliberately written to provide no exploitable details to the user.) If the user is local, different error details are provided. In the finally block, an open resource is released.

    try
    {
        sqlConnection1.Open();
        sqlDataAdapter1.Fill(dsCustomers1);
    }
    catch (Exception ex)
    {
        if(Request.IsLocal)
        { Session["CurrentError"] = ex.Message; }
        else
        { Session["CurrentError"] = "Error processing page."; }
        Server.Transfer("ApplicationError.aspx");
    }
    finally
    {
        this.sqlConnection1.Close();
    }
 

--Microsoft
 For Support