16.5. The try and catch StatementsAs you saw, the exception in your previous example stopped your program dead. That's usually not the desired behavior. What you need is a way to tell the compiler, "If any exceptions are thrown in this section of code, take this action." That way, your program can continue on from the error, or at least end gracefully. This process is called handling the exception. To handle exceptions, take the following steps:
A try block is created using the keyword try and is enclosed in braces. The try block is the area of code where you want to watch for exceptions. A catch block holds the code where you take action based on the type of exception thrown. It is created using the keyword catch and is also enclosed in braces. Example 16-2 illustrates these constructs. Note that Example 16-2 is identical to Example 16-1 except that now the program includes a TRy / catch block. Example 16-2. Try and catch blocks
The output looks like this: Enter Main... Enter Run... Enter Func1... Enter Func2... Entering try block... Exception caught and handled! Exit Func2... Exit Func1... Exit Run... Exit Main... Following the try statement is the catch statement. In a real catch statement, you might silently fix the problem (for example, by retrying a database connection), or you might interact with the user to solve the problem (such as offering the user the opportunity to close other applications and free up memory). In Example 16-2, the catch statement simply reports that the exception has been caught and handled. Notice that the exit statements are now written. With the exception handled, execution resumes immediately after the catch block. |