An exception is an error event that happens during the execution of a program, and it disrupts the normal flow of the program's instructions. When an error occurs, the program throws an exception, which must be caught and handled in some way. If not handled, the program usually crashes.
In C++, exception handling involves three keywords: try
, catch
, and throw
.
try
: This block contains any code that might throw an exception. Thetry
keyword is followed by a block of code within braces{}
.throw
: When an error condition occurs within atry
block, the program throws an exception by using thethrow
keyword followed by an exception value. This value can be any of the built-in data type values or an object of a user-defined exception class.catch
: This block is used to handle the exception. It follows thetry
block and catches an exception thrown within thetry
block. The type of exception it can catch must be specified inside parentheses following thecatch
keyword. If the type matches the exception thrown, this block will execute.
#include <iostream> #include <stdexcept> using namespace std; int GetWeight() { int weightParam; // User defined weight // Get user data cout << "Enter weight (in pounds): "; cin >> weightParam; // Error checking, non-negative weight if (weightParam < 0) { throw runtime_error("Invalid weight."); } return weightParam; } int GetHeight() { int heightParam; // User defined height // Get user data cout << "Enter height (in inches): "; cin >> heightParam; // Error checking, non-negative height if (heightParam < 0) { throw runtime_error("Invalid height."); } return heightParam; } int main() { int weightVal; // User defined weight (lbs) int heightVal; // User defined height (in) float bmiCalc; // Resulting BMI char quitCmd; // Indicates quit/continue quitCmd = 'a'; while (quitCmd != 'q') { try { // Get user data weightVal = GetWeight(); heightVal = GetHeight(); // Calculate BMI and print user health info if no input error // Source: http://www.cdc.gov/ bmiCalc = (static_cast<float>(weightVal) / static_cast<float>(heightVal * heightVal)) * 703.0; cout << "BMI: " << bmiCalc << endl; cout << "(CDC: 18.6-24.9 normal)" << endl; } catch (runtime_error &excpt) { // Prints the error message passed by throw statement cout << excpt.what() << endl; cout << "Cannot compute health info." << endl; } // Prompt user to continue/quit cout << endl << "Enter any key ('q' to quit): "; cin >> quitCmd; } return 0; }
Suppose getWeight() throws an exception of type Exception. GetWeight() immediately exits, up to main() where the call was in a try block, so the catch block catches the exception.
Note the clarity of the code in main(). Without exceptions, GetWeight() would have had to somehow indicate failure, perhaps returning -1. Then main() would have needed an if-else statement to detect such failure, obscuring the normal code.
If no handler is found going up the call hierarchy, then terminate() is called, which typically aborts the program.