Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

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.

  1. try: This block contains any code that might throw an exception. The try keyword is followed by a block of code within braces {}.

  2. throw: When an error condition occurs within a try block, the program throws an exception by using the throw 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.

  3. catch: This block is used to handle the exception. It follows the try block and catches an exception thrown within the try block. The type of exception it can catch must be specified inside parentheses following the catch keyword. If the type matches the exception thrown, this block will execute.

Code Block
languagecpp

#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;
}

...