O'Reilly logo

Learning C# 2005, 2nd Edition by Brian MacDonald, Jesse Liberty

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

Chapter 16. Throwing and Catching Exceptions

Things go wrong. Programmers always need to plan for the inevitable problems that might arise while their program is running: networks go down, disks fail, computers exhaust their memory, and so forth.

In C#, you address these problems with exceptions. An exception is an object that encapsulates information about an unusual program occurrence. When an exceptional circumstance arises, an exception is “thrown.” You might throw an exception in your own methods (for example, if you realize that an invalid parameter has been provided), or an exception might be thrown in a class provided by the Framework Class Library (for example, if you try to write to a read-only file). Many exceptions are thrown by the .NET runtime when the program can no longer continue due to an operating system problem (such as a security violation).

Tip

Throwing an exception is sometimes called raising an exception.

Your job as programmer is to try potentially dangerous code, and if an exception is thrown, you catch the exception in your "catch block.”

Tip

Both try and catch are keywords in C#. Catching an exception is sometimes referred to as handling the exception.

Ideally, after the exception is caught, the program can fix the problem and continue. Even if your program can’t continue, by catching the exception, you have an opportunity to print a meaningful error message and terminate gracefully.

Bugs, Errors, and Exceptions

It is important to distinguish exceptions from ...

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