6.1 Using trycatch blocks

 <  Day Day Up  >  

6.1 Using try / catch blocks

You realize that a certain block of code might throw an exception, so you want to create a handler to catch the exception if it is thrown.


Technique

Wrap the code that might throw an exception within a try block. A try block consists of the try keyword and a body within curly braces. If an exception is thrown within that body, the catch handler will execute. The catch block contains the keyword catch followed by the exception type you want to catch and an optional variable identifier for that exception. The body of the catch block contains the code necessary to respond to that exception, as shown in Listing 6.1.

Listing 6.1 Using a try / catch Block to Handle Exceptions
 using System; namespace _1_TryCatch {     class Class1     {         [STAThread]         static void Main(string[] args)         {             try             {                 // ask for and read a number from the user                 Console.Write("Enter a number: ");                 int input = Int32.Parse(Console.ReadLine());                 // the last iteration in this loop will attempt to                 // divide by zero                 for(int i = 5; i >= 0; i)                     Console.WriteLine("{0}/{1}={2}", input, i, input/i);             }             catch(Exception e)             {                 // display exception message                 Console.WriteLine("An error occurred: {0}", e.Message);             }         }     } } 

Comments

In Listing 6.1, you can see an obvious error. As the counter for the loop reaches 0, the program attempts to divide using that value. Naturally, you just want to change the code rather than use exception handling in this case, but sometimes such errors aren't easy to discover.

When you wrap a block of code within a try block, you cover every method that is capable of throwing an exception. If any of the method calls or operations within this code block throw an exception, they all share the same catch block. You can, however, fine-tune the catch block to catch different exceptions and react accordingly . To do so, simply create multiple catch blocks. To catch the divide-by-zero exception in Listing 6.1, for example, create a second catch block whose parameter is DivideByZeroException . Note that by using Exception as the exception class to catch, you will catch any exception that occurs regardless of the type that is thrown.

Furthermore, if an exception is caught within a catch block, the remaining catch blocks do not execute. When the exception is thrown within the code listing that follows , it is caught in the first catch block and not the catch block that follows:

 
 try {     // divide by zero code here } catch(DivideByZeroException) { } catch(Exception) { } 

If the exception is not handled, the Common Language Runtime (CLR) exception dialog appears, as shown in Figure 6.1. When you close the dialog, the runtime accesses the Message and StackTrace properties of the exception object and displays that information within the console, assuming it is a console application. Furthermore, because the exception was not handled using the techniques described in this recipe, the runtime will prematurely abort the application. If, on the other hand, you do handle the exception using a catch block, your program continues at the next instruction following the last catch block. This behavior allows your application to continue even though an error was detected . For instance, in the example shown earlier, if the results of the computation are placed into an array, you can simply skip the computation that caused the divide-by-zero error and continue processing those results, perhaps logging an error along the way.

Figure 6.1. Unhandled exceptions result in the display of the CLR exception dialog.

graphics/06fig01.gif

 <  Day Day Up  >  


Microsoft Visual C# .Net 2003
Microsoft Visual C *. NET 2003 development skills Daquan
ISBN: 7508427505
EAN: 2147483647
Year: 2003
Pages: 440

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net