Throwing Exceptions

throw keyword and exception types

Interview Relevant: Error propagation

Throwing Exceptions

Signal errors by throwing exception objects.

Code Examples

Throwing exceptions to signal errors.

cpp
1void divide(int a, int b) {
2    if (b == 0) {
3        throw runtime_error("Division by zero!");
4    }
5    cout << a / b << endl;
6}
7
8// Throw any type (but prefer exception classes)
9throw 42;              // Not recommended
10throw "Error";         // Not recommended
11throw runtime_error("Error");  // Recommended
12
13// Rethrow current exception
14try {
15    riskyOperation();
16} catch (...) {
17    log("Error occurred");
18    throw;  // Rethrow same exception
19}
20
21// Throw with expression
22void validate(int age) {
23    if (age < 0 || age > 150) {
24        throw out_of_range("Age must be 0-150, got: " + to_string(age));
25    }
26}

AI Tutor

Ask about the topic

Sign in Required

Please sign in to use the AI tutor

Sign In