Exception Handling

C# supports a structured exception handling model that's based on an exception object. The exception handling syntax in C# is similar to the try/catch/finally syntax in C++. Listing A.28 shows an example of this syntax.

Listing A.28. try/catch/finally Syntax
try{
   int zero = 0;
   int divideByZero = 100/zero;
} catch(DivideByZeroException e){
   Console.WriteLine(e.Message);
} finally{
   Console.WriteLine("This is always executed.");
}

The try portion of this block is wrapped around the suspect code. This example is an obvious attempt to create a divide-by-zero exception.

In the catch portion, an error will be dealt with. The catch statement's DivideByZeroException object parameter is the type of exception that will be dealt with; ...

Get Building e-Commerce Sites with the .NET Framework now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.