The try block contains a statement or statements that can throw an exception. A program throws an exception by executing a throw statement. The throw statement generally occurs within a function. For example:
void SetFieldValue(DF *dataField, int userValue)
{
if ((userValue < 0) || userValue > 10)
throw EIntegerRange(0, 10, userValue);
. . .
}
Another part of the program can catch the thrown exception object and handle it accordingly. For example:
try
{
SetFieldValue(dataField, userValue);
}
catch (EIntegerRange &rangeErr)
{
printf("Expected value between %d and %d, but got %d\n",
rangeErr.min, rangeErr.max, rangeErr.value);
}
In the previous example, if the function SetFieldValue finds that its input parameters are invalid, it can throw an exception to indicate this. The try/catch block wrapping SetFieldValue to catch the exception that SetFieldValue throws, and executes the printf statement. If no exception is thrown, the printf statement will not be executed.
A try block specified by try must be followed immediately by the handler specified by catch. The try block is a statement that specifies the flow of control as the program executes. If an exception is thrown in the try block, program control is transferred to the appropriate exception handler.
The handler is a block of code designed to handle the exception. The C++ language requires at least one handler immediately after a try block. The program should include a handler for each exception that the program can generate.
Partager