...
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.
Code Block | ||
---|---|---|
| ||
// #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; }main.cpp // ExceptionDemoTwo// // Created by Kevin Roark on 6/30/23. // Exception Demo - This C++ program is designed to calculate the // Body Mass Index (BMI) of a user based on their inputted // weight and height. The program demonstrates exception handling in C++. #include <iostream> #include <stdexcept> // Needed Libray for Exceptions using namespace std; //Prototypes int GetWeight(); int GetHeight(); int main() { int weightVal; // User defined weight (lbs) int heightVal; // User defined height (in) floatdouble bmiCalc; // Resulting BMI char quitCmdquitCommand; // Indicates quit/continue quitCmdquitCommand = 'a'; while (quitCmdquitCommand != '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>cast<double>(weightVal) / static_cast<float>cast<double>(heightVal * heightVal)) * 703.0; cout << "BMI: " << bmiCalc << endl; cout << "(CDC: 18.6-24.9 is 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 >> quitCmdquitCommand; } return 0; } //Functions ************ 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; } |
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.
...
If no handler is found going up the call hierarchy, then terminate() is called, which typically aborts the program.
This Example is designed to calculate a user's Body Mass Index (BMI) based on their inputted weight and height. The program demonstrates exception handling in C++. Here is a breakdown of the key parts:
Main function: The program's execution begins here. It is designed to keep asking the user for their weight and height until the user enters 'q' to quit. For each iteration, the program attempts to calculate and print the BMI. It does so inside a
try
block, where it callsGetWeight()
andGetHeight()
functions, calculates the BMI, and prints it. If the user enters a negative value for either weight or height, an exception is thrown in either theGetWeight()
orGetHeight()
function. This exception is caught in thecatch
block in the main function, and an appropriate error message is printed.GetWeight() function: This function asks the user for their weight, stores it in
weightParam
and returns it. If the weight entered is negative, it throws a runtime error with the message "Invalid weight."GetHeight() function: This function works similarly to the
GetWeight()
function. It asks the user for their height, stores it inheightParam
and returns it. If the height entered is negative, it throws a runtime error with the message "Invalid height."Error Handling: The program uses exception handling to handle cases where the user may enter a negative value for either weight or height. If either
GetWeight()
orGetHeight()
functions encounter a negative value, they throw aruntime_error
exception. This exception is caught in thecatch
block in the main function where an error message is printed.BMI Calculation: The Body Mass Index (BMI) is calculated using the formula
(weight / (height * height)) * 703.0
, where weight is in pounds and height is in inches. The result is a measure of body fat based on weight and height that applies to adult men and women.
This is an example of how exception handling in C++ can be used to handle errors gracefully and provide informative error messages to the user.