Error Handling in C++: A Comprehensive Guide to Exceptions and Try-Catch Blocks - Biz Tech

Error Handling in C++: A Comprehensive Guide to Exceptions and Try-Catch Blocks

Listen
  #include <iostream>
#include <stdexcept>
#include <string>

double divide(double dividend, double divisor) {
    if (divisor == 0) {
        throw std::invalid_argument("Divisor cannot be zero.");
    }
    return dividend / divisor;
}

int main() {
    double dividend, divisor;

    std::cout << "Enter dividend: ";
    std::cin >> dividend;
    std::cout << "Enter divisor: ";
    std::cin >> divisor;

    try {
        double result = divide(dividend, divisor);
        std::cout << "The result of the division is: " << result << std::endl;
    } catch (const std::invalid_argument& e) {
        std::cerr << "Error: " << e.what() << std::endl;
    } catch (...) {
        std::cerr << "An unknown error occurred." << std::endl;
    }

    return 0;
}

This code block demonstrates error handling in C++ using exceptions and try-catch blocks. The program defines a divide function that throws an std::invalid_argument exception if the divisor is zero. In the main function, the user inputs dividend and divisor values, and the divide function is called within a try-catch block. If an exception is thrown, it is caught and an appropriate error message is displayed.