Labs ICT
โญ Pro Login

Exceptions

1 min read | C++ Tutorial
โญ

Want the full learning experience?

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

Explore Pro Courses

Exceptions

An exception is an unexpected event that disrupts normal program flow. C++ provides throw to signal an exception and try/catch to handle it.

Throwing Exceptions

Use the throw keyword followed by an expression. You can throw values of any type: integers, strings, or custom objects.

#include <iostream>
using namespace std;

double divide(double a, double b) {
  if (b == 0) {
    throw "Division by zero";
  }
  return a / b;
}

int main() {
  double x = 10, y = 0;
  try {
    double result = divide(x, y);
    cout << "Result: " << result << "\n";
  } catch (const char* msg) {
    cout << "Error: " << msg << "\n";
  }
  return 0;
}

๐Ÿงช Quick Quiz

Which keyword is used to throw an exception?