⬅ Previous Next ➡

Exception Handling

Exception Handling in C++
  • Exception Handling is used to handle runtime errors without crashing the program.
  • Main keywords: try, throw, catch.
  • Benefits: separates error-handling code from normal code, improves reliability.

1) try, throw, catch (Basic)

  • try block contains code that may generate an exception.
  • throw is used to raise an exception (any type can be thrown).
  • catch block handles the exception.
#include <iostream>
using namespace std;

int main() {
    int a = 10, b = 0;

    try {
        if (b == 0) {
            throw "Division by zero not allowed";
        }
        cout << "Result: " << (a / b) << endl;

    } catch (const char *msg) {
        cout << "Error: " << msg << endl;
    }

    return 0;
}

2) Handling Multiple Exceptions

  • You can use multiple catch blocks for different exception types.
  • Order matters: catch specific exceptions first, general last.
#include <iostream>
using namespace std;

int main() {
    try {
        int x = 5;

        if (x == 0) throw 100;            // int exception
        if (x == 5) throw 2.5;            // double exception
        if (x < 0) throw "Negative value"; // string (const char*)

    } catch (int e) {
        cout << "Caught int: " << e << endl;

    } catch (double e) {
        cout << "Caught double: " << e << endl;

    } catch (const char *msg) {
        cout << "Caught message: " << msg << endl;
    }

    return 0;
}

3) catch(...) (Default Catch Block)

  • catch(...) catches any exception type (unknown/any).
#include <iostream>
using namespace std;

int main() {
    try {
        throw 10;
    } catch (...) {
        cout << "Caught an unknown exception" << endl;
    }

    return 0;
}

4) Standard Exceptions (std::exception)

  • C++ provides built-in exception classes in <exception> and <stdexcept>.
  • Common standard exceptions:
    • std::runtime_error
    • std::out_of_range
    • std::invalid_argument
    • std::bad_alloc (memory allocation failure)
#include <iostream>
#include <stdexcept>
using namespace std;

int main() {
    try {
        int age = -1;
        if (age < 0) {
            throw invalid_argument("Age cannot be negative");
        }
    } catch (const exception &e) {
        cout << "Standard Exception: " << e.what() << endl;
    }

    return 0;
}

5) Custom Exception Class

  • You can create your own exception type by inheriting from std::exception.
  • Override what() to return error message.
#include <iostream>
#include <exception>
using namespace std;

class MyException : public exception {
public:
    const char* what() const noexcept override {
        return "Custom Exception: Invalid operation!";
    }
};

int main() {
    try {
        throw MyException();
    } catch (const exception &e) {
        cout << e.what() << endl;
    }

    return 0;
}

6) Quick Notes

  • try = risky code, throw = raise error, catch = handle error.
  • Use multiple catch blocks for different error types.
  • catch(...) is a universal handler (use carefully).
  • Prefer standard exceptions for real projects.
  • Custom exceptions help create meaningful error messages.
⬅ Previous Next ➡