Exception Handling

Section 7: Exception Handling

Lesson 1: Exception Handling in C++

1.1 try, catch, throw Statements

Exception handling in C++ allows the program to gracefully handle unexpected errors using try, catch, and throw statements.

Example (Exception Handling in C++): 

#include <iostream>


// Custom exception class

class CustomException : public std::exception {

public:

    const char* what() const noexcept override {

        return "Custom Exception!";

    }

};


int main() {

    try {

        // Code that may throw an exception

        int numerator = 10;

        int denominator = 0;


        if (denominator == 0) {

            // Throwing an exception

            throw std::runtime_error("Division by zero");

        }


        // Normal execution if no exception is thrown

        double result = static_cast<double>(numerator) / denominator;

        std::cout << "Result: " << result << std::endl;

    } catch (const std::exception& e) {

        // Catching and handling the exception

        std::cerr << "Exception: " << e.what() << std::endl;

    }


    return 0;

}


1.2 Exception Classes and Customization

Custom exception classes can be created by deriving from std::exception to provide specific information about the error.

Example (Custom Exception Class in C++): 

#include <iostream>


// Custom exception class

class CustomException : public std::exception {

public:

    // Constructor with a custom error message

    CustomException(const char* message) : errorMessage(message) {}


    // Overriding the what() function to return the error message

    const char* what() const noexcept override {

        return errorMessage.c_str();

    }


private:

    std::string errorMessage;

};


int main() {

    try {

        // Code that may throw a custom exception

        throw CustomException("Custom Exception Thrown!");

    } catch (const std::exception& e) {

        // Catching and handling the exception

        std::cerr << "Exception: " << e.what() << std::endl;

    }


    return 0;

}

Understanding and implementing exception handling in C++ is essential for creating robust programs that gracefully handle errors. Practice using try, catch, and throw statements and consider creating custom exception classes for specific error scenarios.