Chapter 16. Throwing and Catching Exceptions

Things go wrong. Programmers always need to plan for the inevitable problems that 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 contains information about an unusual program occurrence. When an exceptional circumstance arises, an exception is “thrown.” (You’ll also hear that an exception is raised.) 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, or FCL (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).

Your job as programmer is to try potentially dangerous code—that is, to mark out code that might throw an exception. If an exception is thrown, you catch the exception by writing appropriate code in your "catch block.” Both try and catch are keywords in C#. Catching an exception is sometimes referred to as handling the exception, and the catch block is often called an exception handler.

Ideally, you can provide some code in the catch block so that when 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—that is, your program ends and tells the user what happened and why, instead of simply crashing.

This chapter describes how to write your programs to catch and handle exceptions. This chapter also shows you how to use the properties of the Exception class to provide information to the user about what went wrong, and it shows you how to create and use your own custom exception types.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset