Geek Slack

Learn C++
About Lesson


C++ Exceptions


C++ Exceptions

Exceptions in C++ are a way to handle errors or exceptional situations during program execution. They provide a way to transfer control from one part of the program to another in a structured manner.

1. Example of Throwing and Catching Exceptions

Example demonstrating throwing and catching exceptions:

#include <iostream>
#include <stdexcept>

// Function that throws an exception
double divide(double a, double b) {
    if (b == 0) {
        throw std::invalid_argument("Division by zero error");
    }
    return a / b;
}

int main() {
    double x = 10.0, y = 0.0, result;

    try {
        // Attempt to divide x by y
        result = divide(x, y);
        std::cout << "Result of division: " << result << std::endl;
    } catch (std::exception& e) {
        // Catch and handle the exception
        std::cerr << "Exception caught: " << e.what() << std::endl;
    }

    return 0;
}

2. Multiple Catch Blocks

Example demonstrating multiple catch blocks for different exception types:

#include <iostream>
#include <stdexcept>
#include <fstream>

// Function that throws exceptions
void openFile(const std::string& filename) {
    std::ifstream file(filename);

    if (!file.is_open()) {
        throw std::runtime_error("Failed to open file");
    }
}

int main() {
    std::string filename = "nonexistent.txt";

    try {
        // Attempt to open a file
        openFile(filename);
        std::cout << "File opened successfully." << std::endl;
    } catch (const std::runtime_error& e) {
        // Catch and handle runtime_error
        std::cerr << "Runtime error caught: " << e.what() << std::endl;
    } catch (...) {
        // Catch any other exceptions
        std::cerr << "Unknown exception caught." << std::endl;
    }

    return 0;
}

3. Exception Specifications (Deprecated)

Example demonstrating deprecated exception specifications:

#include <iostream>

// Function with exception specification (deprecated)
void myFunction() throw(int, double) {
    // Code that may throw int or double
    throw 10; // Example of throwing an int
}

int main() {
    try {
        myFunction();
    } catch (int e) {
        std::cerr << "Exception caught: " << e << std::endl;
    } catch (...) {
        std::cerr << "Unknown exception caught." << std::endl;
    }

    return 0;
}

Conclusion

C++ exceptions provide a structured way to handle errors and exceptional situations during program execution. This chapter covered throwing and catching exceptions using try-catch blocks, handling multiple types of exceptions with different catch blocks, and briefly mentioned the deprecated exception specifications. Understanding exception handling in C++ is crucial for writing robust and error-tolerant programs.

Join the conversation