Handling Exceptions






Handling Exceptions

You can handle exceptions in Visual C# .NET programs by using a combination of these exception handling statements: try, catch, finally, and throw.

The try Block

You should place code that might cause exceptions in a try block. A typical try block looks similar to the following:

try
{
    // code that may cause exception
}

When an exception occurs at any point, rather than executing any further, the CLR searches for the nearest try block that encloses the exceptional code. The control is then passed to a matching catch block (if any) and then to the finally block (if any) associated with this try block.

A try block cannot exist on its own; it must be immediately followed either by one or more catch blocks or by a finally block.

The catch Block

You can have several catch blocks immediately following a try block. When an exception occurs in a statement placed inside the try block, the CLR looks for a matching catch block capable of handling that type of exception. A typical try-catch block looks like this:

try
{
    // code that may cause exception
}
catch(ExceptionTypeA)
{
    // Statements to handle errors
    // occurring in the associated try block
}
catch(ExceptionTypeB)
{
    // Statements to handle errors occurring
    // in the associated try block
}

The formula the CLR uses to match the exception is simple: It looks for the first catch block with either the same exception or any of the exception's base classes. For example, a DivideByZeroException exception would match with any of these exceptions: DivideByZeroException, ArithmeticException, SystemException, and Exception. In the case of multiple catch blocks, only the first matching catch block is executed and all other catch blocks are ignored.

graphics/note_icon.gif

If no matching catch block exists, an unhandled exception occurs and is propagated back to its caller code (the code that called the current method). If the exception is not handled there, it propagates further up the hierarchy of method calls. If the exception is not handled anywhere, it goes to the CLR for processing. The CLR's default behavior is to immediately terminate the processing of the Web page and display error messages.


When you write multiple catch blocks, you need to arrange them from specific exception types to more general exception types. For example, the catch block for catching the DivideByZeroException exception should always precede the catch block for catching the ArithmeticException exception because the DivideByZeroException exception derives from the ArithmeticException exception and is therefore more specific than ArithmeticException. The compiler flags an error if you do not follow this rule.

A try block need not necessarily have a catch block associated with it; however, in that case, it must have a finally block associated with it.

The finally Block

You use the finally block to write cleanup code that maintains your application in a consistent state and preserves the external environment. For example, you can write code to close files, database connections, and related input/output (I/O) resources in a finally block.

A try block doesn't have to have an associated finally block. However, if you do write a finally block, you cannot have more than one, and the finally block must appear after all the catch blocks.

The finally block can be used in the form of a try-finally block without any catch block between them. Here's an example:

try
{
   // Write code to allocate some resources
}
finally
{
   // Write code to dispose all allocated resources
}

This use ensures that allocated resources are properly disposed of, no matter what happens in the try block. In fact, Visual C# .NET provides a using statement that does exactly the same job but with less code to write. A typical use of the using statement is as follows:

// Write code to allocate some resource list the allocated resources
in a comma-separated list inside the parentheses of the using block
using(...)
{
  // use the allocated resource
}
// Here, the Dispose() method is called automatically for all the
// objects referenced in the parentheses of the using statement

The following example shows you how to use a try-catch-finally block to handle exceptions:

  1. Create a new Visual C# ASP.NET Web application project in the Visual Studio .NET IDE. Specify the location of the project as http://localhost/ExamCram/315C05.

  2. Add a new Web form to the project, and name it Example5_1.aspx.

  3. Place three TextBox controls (txtMiles, txtGallons, and txtEfficiency) and a Button (btnCalculate) on the Web form's surface and arrange them as shown in Figure. Add the Label controls as necessary.

    1. The Mileage Efficiency Calculator Web form implements exception handling for the user interface.

    graphics/05fig01.jpg

  4. Attach a Click event handler to the btnCalculate control and add the following code to it:

    private void btnCalculate_Click(object sender, System.EventArgs e)
    {
        try
        {
            decimal decMiles = Convert.ToDecimal(txtMiles.Text);
            decimal decGallons = Convert.ToDecimal(txtGallons.Text);
            decimal decEfficiency = decMiles/decGallons;
            txtEfficiency.Text = String.Format("{0:n}", decEfficiency);
        }
        catch (FormatException fe)
        {
            string msg = String.Format(
                "Message: {0}<br> Stack Trace:<br> {1}",
                fe.Message, fe.StackTrace);
            lblMessage.Text = fe.GetType().ToString() +
                "<br>"  + msg + "<br>";
        }
        catch (DivideByZeroException dbze)
        {
            string msg = String.Format(
                "Message: {0}<br> Stack Trace:<br> {1}",
                dbze.Message, dbze.StackTrace);
            lblMessage.Text = dbze.GetType().ToString() +
                "<br>"  + msg + "<br>";
        }
        // Catches all CLS-compliant exceptions
        catch(Exception ex)
        {
            string msg = String.Format(
                "Message: {0}<br> Stack Trace:<br> {1}",
                ex.Message, ex.StackTrace);
            lblMessage.Text = ex.GetType().ToString() +
                "<br>"  + msg + "<br>";
        }
        // Catches all other exceptions including the
        // Non-CLS compliant exceptions
        catch
        {
            // Just rethrow the exception to the caller
            throw;
        }
        // Use finally block to perform cleanup operations
        finally
        {
            lblMessage.Text += "Finally block always executes " +
                " whether or not exception occurs" + "<br>";
        }
    }
    
  5. Set the Web form as the start page for the project and run the project. Enter values for miles and gallons and click the Calculate button. The program calculates the mileage efficiency, as expected. Now enter the value 0 in the Gallons of Gas Used field; the program shows a message about the DivideByZeroException exception (as shown in Figure) and continues running. Now enter some alphabetic characters in the fields and click the Calculate button. This time you get a FormatException message and the program continues to run. Now try entering a large value for both fields. If the values are large enough, the program encounters an OverflowException exception, but continues running.

    Figure. To get information about an exception, catch the exception object and access its Message property.

    graphics/05fig02.jpg

graphics/alert_icon.gif

All languages that follow the Common Language Specification (CLS) throw exceptions of type System.Exception or a type that derives from System.Exception. A non-CLS-compliant language might throw exceptions of other types, too. You can catch those types of exceptions by placing a general catch block (one that does not specify any exception) with a try block. In fact, a general catch block can catch exceptions of all types, so it is the most generic of all catch blocks and should be the last catch block among the multiple catch blocks associated with a try block.


graphics/alert_icon.gif

If you have a finally block associated with a try block, the code in the finally block always executes whether an exception occurs or not. In addition, if a transfer-control statement such as goto, break, or continue exists in either the try or the catch block, the control transfer happens only after the code in the finally block is executed. The Visual C# .NET compiler does not allow you to put a transfer-control statement such as goto inside a finally block.


The throw Statement

A throw statement explicitly generates an exception in code. You use throw when a particular path in code results in an anomalous situation.

There are two ways you can use the throw statement. In its simplest form, you can just rethrow the exception in a catch block:

catch(Exception e)
{
    //TODO: Add code to create an entry in event log
    throw;
}

This use of the throw statement rethrows the exception that was just caught. It can be useful in situations in which you do not want to handle the exception yourself but would like to take other actions (for example, recording the error in an event log or sending an email notification about the error) when an exception occurs. Then, you can pass the exception as is to its caller.

The second way of using a throw statement is to use it to throw explicitly created exceptions, as in this example:

string strMessage = "EndDate should be greater than the StartDate";
ArgumentOutOfRangeException newException =
     new ArgumentOutOfRangeException(strMessage);
throw newException;

In this example, you first create a new instance of the ArgumentOutOfRangeException object and associate a custom error message with it; then you throw the newly created exception.

You are not required to put this usage of the throw statement inside a catch block because you are just creating and throwing a new exception, rather than rethrowing an existing one. You typically use this technique to raise your own custom exceptions.

graphics/alert_icon.gif

When you create an exception object, you should use the constructor that allows you to associate a custom error message rather than use the default constructor. The custom error message can pass specific information about the cause of the error, as well as a possible way to resolve it.


graphics/caution_icon.gif

The throw statement is an expensive operation. Use of throw consumes significant system resources as compared to just returning a value from a method. You should therefore use the throw statement cautiously and only when necessary because it has the potential to make your programs slow.


An alternative way of rethrowing an exception is to throw it after wrapping it with additional useful information, like so:

catch(ArgumentNullException ane)
{
   // TODO: Add code to create an entry in the log file
   string strMessage = "CustomerID cannot be null";
   ArgumentNullException newException =
       new ArgumentNullException(strMessage, ane);
   throw newException;
}

You might need to catch an exception that you cannot handle completely. You would then perform any required processing and throw a more relevant and informative exception to the caller code so it can perform the rest of the processing. In this case, you can create a new exception whose constructor wraps the previously caught exception in the new exception's InnerException property. The caller code then has more information available to handle the exception appropriately.


     Python   SQL   Java   php   Perl 
     game development   web development   internet   *nix   graphics   hardware 
     telecommunications   C++ 
     Flash   Active Directory   Windows