722 Day 20
tryBlocks
A tryblock is a series of statements that begins with the keyword try; it is followed by
an opening brace and ends with a closing brace.
Example
try
{
Function();
};
catchBlocks
A catchblock is a piece of code that begins with the keyword catch, followed by an
exception type in parentheses, followed by an opening brace, and ending with a closing
brace. catchblocks are only allowed to follow a tryblock.
Example
try
{
Function();
};
catch (OutOfMemory)
{
// take action
}
Causing Your Own Exceptions ......................................................................
Listing 20.2 illustrated two of the aspects of exception handling—marking the code to be
watched and specifying how the exception is to be handled. However, only predefined
exceptions were handled. The third part of exception handling is the ability for you to
create your own types of exceptions to be handled. By creating your own exceptions, you
gain the ability to have customized handlers (catchblocks) for exceptions that are mean-
ingful to your application.
To create an exception that causes the trystatement to react, the keyword,throw,is
used. In essence, you throwthe exception and, hopefully, a handler (catchblock) catches
it. The basic format of the throwstatement is:
throw exception;