| Tracing, Debugging and Error Handling Techniques |
| |
| Exception and Error Handling |
| |
| After taking all precautions, no matter what you do, some errors will always have a chance to occur (e.g. error if you want to parse an integer out of a textbox and the user enters a normal string or even an invalid number). The last thing you want is to show those errors to the user so you'll have to handle all the possible exceptions. This can be done on several levels. |
| |
| There are three ways to handle exceptions/errors in ASP.NET: |
| |
1. Try-catch block. This is also called Structured Exception Handling (SEH).
2. Error Events.
3. Custom Error Page. |
| |
| Using try-catch Block |
| |
| The first place where you should handle exceptions is where you generate them yourself (by throwing a new exception) or where you know exceptions are very possible to occur (divide by 0, missing database link, ...). This is simply done by adding try/catch/finally around the risky code fragments. The finally part is optional and is used in case you want something to happen no matter if there is an exception or not. |
| |
| But be ready! Some exceptions are absolutely unexpected or you just forgot one of the possible exceptions while handling the rest. You can catch these on page level by overriding the standard OnError event. After handling the exception and maybe generating some output to a log or the screen you can kill the error and prevent it to go further to application level with Server.ClearError(). |
| |
| Enclose code that accesses files, databases, and so forth inside a try-catch block because access to those resources might be denied due to various reasons causing an exception. The third part of this block is finally. It is executed irrespective of the fact that an exception has been raised. Hence, use the finally block to complete the housekeeping jobs. |
| |
| As a good programming practice, always catch specific exceptions. To view the exception types supported by the .NET Framework, use the Debug menu and select Exceptions in Visual Studio.NET. |
| |
| In the following code, the first sample code1 is used to handle the exception occurs due to integer value and next sample code2 is to try to access a table that does not exist in the Northwind database; therefore, an exception is raised. By using the try catch and finally block, you handle the exception and display a message. |
| |
Sample Code1:
protected void mybutton_Click(object sender, EventArgs e)
{
int x;
try
{
x = int.Parse(txtGetal.Text);
for (int i = x; i >= 0; i--)
x *= i;
mylabel.Text = PrintText(x.ToString());
}
catch (OverflowException ex)
{
mylabel.Text = "Number to big!";
}
}
protected override void OnError(EventArgs e)
{
Exception objErr = Server.GetLastError().GetBaseException();
string err = "Error Caught in Application_Error event\n" +
"Error in: " + Request.Url.ToString() +
"\nError Message:" + objErr.Message.ToString();
Response.Write(err.ToString());
//Server.ClearError(); // kills the exception
// forward to application level
}
Sample Code2:
try
{
con = new SqlConnection("integrated security=SSPI;
data source= (local);persist security info=False;
initial catalog=Northwind");
da = new SqlDataAdapter("Select * from TblNotExisits", con);
ds = new DataSet();
da.Fill(ds);
}
catch(SqlException ex)
{
return "Connection Unsuccessful " + ex.Message;
}
finally
{
con.Dispose();
}
return "Connection Successful"; |
| |
| Using Error Events |
| |
| In ASP.NET, there are three different error events that can be used in combination with Structured Exception Handling so that all exceptions are handled and the user is presented with a user-friendly error message. |
| |
1. Page_Error: Occurs when an error occurs within the Web page. This event is in the Web form.
2. Global_Error: Occurs when an error occurs within the application. This event is in the Gloabl.asax file.
3. Application_Error: Occurs when an error occurs within the application. This event is in the Gloabl.asax file. |
| |
| Methods in the Server object are used to handle the exception in the error events. |
| |
1. GetLastError: Gets the last exception that occurred on the server.
2. ClearError: Use this method to handle the exception and stop the error to trigger the subsequent error event or display the error to the user. |
| |
| In the following code, you handle the exception in all the above three mentioned events but call the ClearError method only in the Application_Error event so that the error is propogated to the above level. |
| |
private void Page_Error(object sender, System.EventArgs e)
{
Exception ex = Server.GetLastError();
Response.Write("Handled error from Page<br>");
//Server.ClearError();
}
protected void Application_Error(Object sender, EventArgs e)
{
Exception ex = Server.GetLastError();
Response.Write("Handled error from Application <br>");
Server.ClearError();
}
protected void Global_Error(Object sender, EventArgs e)
{
Exception ex = Server.GetLastError();
Response.Write("Handled error from Global <br>");
} |
| |
| Using Custom Error Pages |
| |
| Use custom error page to handle HTTP exceptions such as page not found, unauthorized access, and so forth. You can specify custom error pages in two places: |
| |
1. CustomErrors: The customErrors section of the web.config file. This setting specifies the application-wide error page to display for unhandled HTTP errors. HTTP errors are identified by the HTTP status code. Include the <error> tag in the customErrors to display a status code-specific error page. Does not work with .php or .php files. Set the mode attribute to "On" to view the error page locally.
2. ErrorPage: The errorPage attribute of the @Page directive of the Web form to display the error page for the error generated on the particular Web form. |
| |
| Using this method you might consider adding some user-friendly error pages since you don't want them to get stuck in the generated error page. It also looks more professional if you warn the user with a nice message like "There has been an unexpected error, the administrator has been informed. Please try again later." You can create this error page yourself and by adding some extra code to your Web.config file your site can crash with style. |
| |
<customErrors mode="On" defaultRedirect="~/Error.aspx">
<error statusCode="404" redirect="~/Error.aspx?code=404" />
<error statusCode="408" redirect="~/Error.aspx?code=408" />
<error statusCode="505" redirect="~/Error.aspx?code=505" />
</customErrors> |
| |
| In above written code the customsError section in the web.config file specifies the application to redirect to Error404.aspx file if a non-existent file is requested. |
| |
| The @Page directive specifies the error page to be redirected to if an error occurs in the Web page. |
| |
<%@ Page language="c#" Codebehind="PageErr.aspx.cs"
AutoEventWireup="false"
Inherits="ExceptionHandling.PageErr"
errorPage="Error.aspx" %> |
| |
|
| |