C++ Exceptions

C++ Exceptions (Try, Throw, Catch)

When executing C++ code, runtime errors can occur. For example, a user might enter invalid data, a file might be missing, or a calculation might attempt to divide by zero.

Instead of letting the program crash abruptly, C++ allows you to "catch" these errors and handle them gracefully using Exceptions.

Exception handling in C++ consists of three keywords: try, throw, and catch.


The Try, Throw, and Catch Keywords

Syntax Overview

try {
  // Block of code to try
  throw exception; // Throw an error when a problem arise
}
catch () {
  // Block of code to handle errors
}

Example: Age Validation

Let's look at a practical example. We want to check a user's age. If they are 18 or older, they are granted access. If they are under 18, we will throw an exception.

Exception Example

#include <iostream>
using namespace std;

int main() { try { int age = 15; if (age >= 18) { cout << "Access granted - you are old enough."; } else { // Throw an error code (we chose the integer 505) throw 505; } } catch (int myNum) { cout << "Access denied - You must be at least 18 years old.\n"; cout << "Error number: " << myNum; }

return 0; }

How it works:

  1. The program enters the try block.
  2. The if statement checks the age. Because 15 is less than 18, the else block triggers.
  3. The throw 505; statement immediately stops the try block and looks for a catch block that accepts integers.
  4. The catch (int myNum) block takes over, printing our custom error message and the error code 505.

Catching Any Exception (catch (...))

Sometimes, you might not know exactly what type of exception will be thrown (it could be an int, a string, or an object). If you want your catch block to handle any type of exception, use three dots ... inside the catch parentheses.

Catch All Example

try {
  int age = 15;
  if (age < 18) {
    throw "Not old enough!"; // Throwing a string this time
  }
}
catch (...) { // Catches any type of exception
  cout << "Access denied!";
}

Exercise

?

Which keyword is used to generate a custom error in C++?