Labs ICT
โญ Pro Login

Exceptions

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;
}
Try it Yourself โ†’

๐Ÿงช Quick Quiz

Which keyword is used to throw an exception?