Introduction
In this chapter, we introduce exception handling. An exception is an indication of a problem that occurs during a program's execution. The name "exception" comes from the fact that, although the problem can occur, it occurs infrequently. If the "rule" is that a statement normally executes correctly, then the occurrence of a problem represents the "exception to the rule." Exception handling enables programmers to create applications that can resolve (or handle) exceptions. In many cases, handling an exception allows a program to continue executing as if no problems were encountered. However, more severe problems may prevent a program from continuing normal execution, instead requiring the program to notify the user of the problem, then terminate in a controlled manner. The features presented in this chapter enable programmers to write clear, robust and more fault-tolerant programs (i.e., programs that are able to deal with problems that may arise and continue executing). The style and details of C# exception handling are based in part on the work of Andrew Koenig and Bjarne Stroustrup. "Best practices" for exception handling in Visual C# 2005 are specified in the Visual Studio documentation.[1]
[1] "Best Practices for Handling Exceptions [C#]," .NET Framework Developer's Guide, Visual Studio .NET Online Help. Available at msdn2.microsoft.com/library/seyhszts(en-us,vs.80).aspx.
|
This chapter begins with an overview of exception-handling concepts and demonstrations of basic exception-handling techniques. The chapter also overviews .NET's exception-handling class hierarchy. Programs typically request and release resources (such as files on disk) during program execution. Often, the supply of these resources is limited, or the resources can be used by only one program at a time. We demonstrate a part of the exception-handling mechanism that enables a program to use a resource, then guarantee that the resource will be released for use by other programs, even if an exception occurs. The chapter demonstrates several properties of class System.Exception (the base class of all exception classes) and discusses how you can create and use your own exception classes.