Chapter 7. Exception Handling
This chapter contains recipes covering the exception-handling mechanism, including the
try, catch, and
finally blocks. Along with these recipes are others covering the mechanisms used to throw exceptions manually from within your code. The final recipes include those dealing with the
Exception classes and their uses, as well as subclassing them to create new types of exceptions.
Often, the design and implementation of exception handling is performed later in the development cycle. But with the power and complexities of C# exception handling, you need to plan and even implement your exception-handling scheme much earlier. Doing so will increase the reliability and robustness of your code while minimizing the impact of adding exception handling after most or all of the application is coded.
Exception handling in C# is very flexible. It allows you to choose a fine- or coarse-grained approach to error handling, or any level between. This means that you can add exception handling around any individual line of code (the fine-grained approach) or around a method that calls many other methods (the coarse-grained approach), or you can use a mix of the two, with mainly a coarse-grained approach and a more fine-grained approach in specific critical areas of the code. When using a fine-grained approach, you can intercept specific exceptions that might be thrown from just a few lines of code. The following method sets an object's property to a numeric ...