Labs ICT
Pro Login

Try & Catch

Try and Catch

The try block contains code that might throw an exception. The catch block handles the exception if one occurs.

Multiple Catch Blocks

You can have several catch blocks to handle different exception types. A catch-all handler catch (...) catches any remaining type.

#include <iostream>
using namespace std;

int main() {
  try {
    int age = 15;
    if (age < 18) {
      throw age;
    }
    cout << "Access granted\n";
  }
  catch (int num) {
    cout << "Access denied. Age: " << num << "\n";
  }
  catch (...) {
    cout << "Unknown error\n";
  }
  return 0;
}
Try it Yourself →