Throwing (or raising) an exception halts execution of your program at that point, and execution proceeds in the most immediately available catch
block (exception handler).
A bug is a programming mistake that should be fixed before the program is released. An exception, however, is the result of a predictable but unpreventable problem that arises during runtime (for example, running out of disk space).
When a program encounters a problem that it cannot solve or work around, it may throw an exception to halt execution and allow the exception handler to fix or work around the problem.
All exceptions used in C# derive from System.Exception
, and all exceptions in your program should derive from System.Exception
.
You can throw an exception yourself using the throw
keyword.
It is good programming practice to enclose code that has a high risk of throwing an exception within a try
block and to provide an exception handler (a catch
block) and perhaps a finally
block.
The catch
block follows the try
block and contains the code used to handle the exception.
If an exception was not raised within a try
block, or there is no catch
block, the stack is unwound until a catch
block is found. If no catch
block is ever found, the built-in exception handler is invoked, which terminates your program with an error message.
You can create dedicated catch
statements to catch specific types of exceptions taking advantage of the inheritance hierarchy of exceptions.
Any action that must be taken whether or not an exception is raised (such as closing a file) should be enclosed in a finally
block.
An exception object can contain information about the circumstances that cause the exception to be raised. Typically, exception objects contain at least a text message explaining the exception, in the Message
property.
You can define your own exception class, derived from System.Exception
, if you need to provide more specific information about your exception.
With this chapter, you’ve taken a step toward the real world of development—you’ve discarded the idea that the world is populated by perfect users who never enter bad data, and perfect systems that never drop your connection when you need it. Although no code is ever bulletproof, yours is no longer made of tinfoil. Now that you can let your programs out of their isolated corner of your system, it’s time to let them interact with other things going on in your environment, things called events. In the next chapter, you’ll see how to let your code play well with others.