Exception Handling in C++ 🚀

 


Exception handling in C++ is a mechanism to handle runtime errors and prevent program crashes. It allows a program to catch and handle errors gracefully using try, catch, and throw.


1️⃣ Exception Handling Keywords

Keyword Description
try Defines a block of code to test for exceptions.
throw Throws an exception when an error occurs.
catch Handles the exception thrown by throw.

2️⃣ Basic Syntax

try {
    // Code that may cause an exception
    throw exceptionType;  // Throwing an exception
}
catch (exceptionType variable) {
    // Handle the exception
}

3️⃣ Example: Divide by Zero Exception

#include <iostream>
using namespace std;

int main() {
    int a, b;
    cout << "Enter two numbers: ";
    cin >> a >> b;

    try {
        if (b == 0)
            throw "Division by zero error!";
        cout << "Result: " << (a / b) << endl;
    } 
    catch (const char* msg) {
        cout << "Exception: " << msg << endl;
    }

    return 0;
}

🔹 Output

Enter two numbers: 10 0
Exception: Division by zero error!

✅ The program does not crash but handles the error safely.


4️⃣ Multiple Catch Blocks

You can use multiple catch blocks to handle different exception types.

#include <iostream>
using namespace std;

int main() {
    try {
        throw 10;   // Change to 'A' or 3.14 to test
    }
    catch (int e) {
        cout << "Integer Exception: " << e << endl;
    }
    catch (char e) {
        cout << "Character Exception: " << e << endl;
    }
    catch (...) {  // Catch-all handler
        cout << "Unknown Exception!" << endl;
    }

    return 0;
}

🔹 Output

Integer Exception: 10

✅ The correct catch block is executed based on the thrown data type.


5️⃣ Exception Handling with Functions

You can throw exceptions from a function and handle them in main().

#include <iostream>
using namespace std;

void checkAge(int age) {
    if (age < 18)
        throw "Age must be 18 or older!";
    cout << "Access granted!" << endl;
}

int main() {
    try {
        checkAge(16);  // Change value to test
    } 
    catch (const char* msg) {
        cout << "Exception: " << msg << endl;
    }

    return 0;
}

🔹 Output

Exception: Age must be 18 or older!

6️⃣ Using std::exception (Built-in Exception Handling)

C++ provides built-in exception handling via the <exception> header.

#include <iostream>
#include <exception>  // Standard exceptions
using namespace std;

int main() {
    try {
        throw runtime_error("Runtime Error Occurred!");
    } 
    catch (exception& e) {
        cout << "Exception: " << e.what() << endl;
    }

    return 0;
}

🔹 Output

Exception: Runtime Error Occurred!

e.what() returns the error message.


7️⃣ noexcept Keyword (Disable Exception Handling)

If a function is marked as noexcept, it cannot throw exceptions.

void myFunction() noexcept {
    throw "Error!";  // This will cause a program crash.
}

🚨 Use noexcept only for functions that should never throw exceptions.


8️⃣ Summary

try - Defines a block of code that may cause an exception.
throw - Throws an exception when an error occurs.
catch - Catches and handles the thrown exception.
✔ Use catch (...) for handling any exception.
std::exception provides built-in error handling.
noexcept disables exception handling.

Would you like an example on custom exception classes? 🚀

Post a Comment

0 Comments