A First Look at Exceptions
Exceptions
Indicate that something unexpected has occurred or been detected
Allow program to deal with the problem in a controlled manner
Can be as simple or complex as program design requires
Terminology
Exception: object or value that signals an error
Throw an exception: send a signal that an error has occurred
Catch/Handle an exception: process the exception; interpret the signal
Key Words
throw – followed by an argument, is used to throw an exception
try – followed by a block { }, is used to invoke code that throws an exception
catch – followed by a block { }, is used to detect and process exceptions thrown in preceding try block. Takes a parameter that matches the type thrown.
Flow of Control
A function that throws an exception is called from within a try block
If the function throws an exception, the function terminates and the try block is immediately exited. A catch block to process the exception is searched for in the source code immediately following the try block.
If a catch block is found that matches the exception thrown, it is executed. If no catch block that matches the exception is found, the program terminates.
Example 1
// function that throws an exception
int totalDays(int days, int weeks) {
if ((days < 0) || (days > 7))
throw string("invalid number of days“);
// the argument to throw is the character string
else
return (7 * weeks + days);
}
Example 2
try // block that calls function {
totDays = totalDays(days, weeks);
cout << "Total days: " << days;
} catch (string msg) // interpret exception {
cout << "Error: " << msg;
}
What Happens
try block is entered. totalDays function is called
If 1st parameter is between 0 and 7, total number of days is returned and catch block is skipped over (no exception thrown)
If exception is thrown, function and try block are exited, catch blocks are scanned for 1st one that matches the data type of the thrown exception. catch block executes
Exceptions and Objects
An exception class can be defined in a class and thrown as an exception by a member function
An exception class may have:
no members: used only to signal an error
members: pass error data to catch block
A class can have more than one exception class
What Happens After catch Block?
Once an exception is thrown, the program cannot return to throw point. The function executing throw terminates (does not return), other calling functions in try block terminate, resulting in unwinding the stack
Last updated
Was this helpful?