C# Exceptions

C# allows a programmer almost all of the functionality provided by the CLR. To demonstrate exception handling in a C# environment, look at the next example that generates exceptions of various types. Because the code is rather long, the listing has been split into small sections. The full source for Listings 15.415.8 is in the BasicExceptions directory. Listing 15.4 shows an example of how C# code can be used to catch a DivideByZeroException.

Listing 15.4. Catching a Divide-By-Zero Exception
// Try a divide by zero
try
{
    int x = 0;
    x = 1/x;
}
catch(DivideByZeroException e)
{
    // Dump interesting exception information
    Console.WriteLine (e.ToString());
}

When the exception is caught, the output looks like this:

 System.DivideByZeroException: ...

Get .NET Common Language Runtime Unleashed now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.