C#'s exception handling is object-oriented in that the exception generated by the execution engine in response to a special condition is an object that contains information about the corresponding abnormal condition. Any such exception object is either of class System.Exception or a subclass thereof. Typical predefined subclasses, found in the .NET Framework class library, are System.DivideByZeroException, System.InvalidOutOfRangeException, and System.NullReferenceException.
When an exceptional condition is encountered in a function, an exception object is created and thrown in that function. The function can catch (handle) the exception object itself or pass it on.
To implement code that monitors and handles exceptions in functions, C# contains the three keywords try, catch, and finally, displayed in Syntax Box 19.1. The try keyword followed by a block of code (enclosed by a pair of curly braces) is called a try block. Similarly, catch forms a catch block (also called an exception handler), and finally forms a finally block.
Any exception objects thrown inside the try block are, as shown in Syntax Box 19.1, compared with each of the following catch blocks to determine if any of these catch blocks were meant to catch this particular exception. This is the case if the exception object is of an exception class that is identical to or a descendant of the catch block parameter type (exemplified with the two placeholders <Exception_class_1> and <Exception_class_2> and the specific class DivideByZeroException in Syntax Box 19.1). If a suitable catch block is found, the exception handling code for this catch block is executed. For example, the exception object of class DivideByZeroException in Syntax Box 19.1 is of the same class as that specified by the third catch block. The code block of this catch block is therefore executed, followed by the execution of the finally block.
If no catch blocks match the DivideByZeroException class, none of the catch blocks are executed and the exception object is passed on. An uncaught exception object is handled by the runtime's default exception-handler, in which case the program is abruptly terminated.
The code in the finally block is always executed. Either finally is executed just before the execution flow exits the try block or, in case a catch block is being executed, just before execution exits that catch block.
Notice that a try block can either
Have one or more associated catch blocks and no finally block
Have one finally block attached and no catch blocks
Include both one or more catch blocks as well as one finally block
Syntax Box 19.1 The try and catch Blocks and the finally Block