Skip to main content

Exception handling constructs

Short answer

try block encloses code that may throw an exception. throw raises an exception with a value. catch block handles a matching exception type; catch(...) catches any. Control resumes after the last catch if exception handled.

Explain about all Exception Handling constructs in C++ (try, catch, throw) with example.

An exception is a run-time error (divide by zero, array index out of range, memory failure). C++ handles exceptions with three keywords.

  1. try – a block of code in which exceptions may occur. If an exception is thrown inside it, control leaves the block at once.
  2. throw – raises (throws) an exception by giving a value or object of some type: throw 10;, throw "error";, throw MyError();
  3. catch – a handler placed immediately after the try block. It catches an exception of a matching type and handles it. catch(...) catches any type.

Syntax:

try {
    // code that may throw
    throw exception_value;
}
catch (type1 arg) {
    // handle type1
}
catch (...) {
    // handle everything else
}

Flow

 try block --throw--> search matching catch --> handler runs
     |                       |                       |
  no exception        no match: terminate()     continue after
  (catch skipped)                               last catch block

Example

#include <iostream>
using namespace std;

int main() {
    int a, b;
    cout << "Enter a and b: ";
    cin >> a >> b;
    try {
        if (b == 0)
            throw "Division by zero";    // throw
        cout << "a/b = " << a / b << endl;
    }
    catch (const char *msg) {            // catch
        cout << "Error: " << msg << endl;
    }
    cout << "Program continues\n";
    return 0;
}

For b = 0 the output is Error: Division by zero followed by Program continues.

✓ Answer checked by Claude Opus 5.5 (high effort)

All Object Oriented Programming chapter 10 questions →