O'Reilly logo

.NET Common Language Runtime Unleashed by Kevin Burton

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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: ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required