|
|
|
|
|
|
|
On line 100, the keyword try begins a try block that ends on line 107. Within that try block, 101 integers are added to the array that was declared on line 99. |
|
|
|
|
|
|
|
|
On line 108, the catch block to catch xBoundary exceptions is declared. |
|
|
|
|
|
|
|
|
try BLOCKS A try block is a set of statements that begin with the word try, are followed by an opening brace, and end with a closing brace. |
|
|
|
| | For example: |  |
|
|
|
|
try
{
Function();
}; |
|
|
|
|
|
|
|
|
|
|
catch BLOCKS A catch block is a series of statements, each of which begins with the word catch, followed by an exception type in parentheses, followed by an opening brace, and ending with a closing brace. |
|
|
|
| | For example: |  |
|
|
|
|
Try
{
Function();
};
Catch (OutOfMemory)
{
// take action
} |
|
|
|
|
|
|
|
|
|
|
Using try Blocks and catch Blocks |
|
|
|
|
|
|
|
|
Figuring out where to put your try blocks is probably the hardest part of using exceptions; it is not always obvious which actions might raise an exception. The next question is where to catch the exception. It may be that you'll want to throw all memory exceptions where the memory is allocated, but you'll want to catch the exceptions high in the program where you deal with the user interface. |
|
|
|
|
|
|
|
|
When trying to determine try block locations, look to where you allocate memory or use resources. Other things to look for are out-of-bounds errors, illegal input, and so forth. |
|
|
|
|
|