codegurukool.com · Free coding tutorials & online compiler

Home › C++ Tutorial › C++ exceptions

C++ exceptions

try, throw, catch.

Throw on error and catch where you can recover. Catch standard errors with exception and what().

Example code

#include <iostream>
#include <stdexcept>
using namespace std;
int main() {
  try {
    int age = 15;
    if (age < 18) throw runtime_error("Too young");
  } catch (const exception &e) {
    cout << e.what() << endl;
  }
  return 0;
}

Run this code in the online editor

← C++ errors and debuggingC++ input validation →