Labs ICT
Pro Login

Try & Catch

1 min read | C++ Tutorial

Want the full learning experience?

Get structured courses, certificates, projects, and instructor support with LabsICT Pro.

Explore Pro Courses

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