» Quick Introduction to C++ » 1. Basics » 1.5 Exception Handling

Exception Handling

Exception handling in C++ is a mechanism that allows you to deal with runtime errors in a more controlled and structured way. It helps separate error-handling code from normal program logic, making code more readable and maintainable.

#include <iostream>
#include <stdexcept>

int divide(int numerator, int denominator) {
    if (denominator == 0) {
        throw std::runtime_error("Division by zero is not allowed.");
    }
    return numerator / denominator;
}

int main() {
    try {
        // Code that might throw an exception
        int numerator = 10;
        int denominator = 0;  // Change this value to test the exception handling
        int result = divide(numerator, denominator);

        std::cout << "Result: " << result << std::endl;
    } catch (const std::exception &e) {
        // Catching and handling exceptions
        std::cerr << "Exception caught: " << e.what() << std::endl;
    }

    return 0;
}

The try block contains the code that might throw an exception. If an exception is thrown during the execution of the try block, the program jumps to the corresponding catch block. In this case, we catch exceptions of type std::exception (and its subclasses) using const exception& e. The what() member function is then used to get the exception message.

The throw statement is used to explicitly throw an exception. In this example, we throw a runtime_error if the user attempts to divide by zero.

Remember, you can catch specific types of exceptions to handle them differently, and you can also have multiple catch blocks to handle different types of exceptions.

Code Challenge

Write a C++ program that simulates a simple password validation system. Implement a function called validatePassword that takes a string representing a password as input and throws an exception if the password doesn't meet the criteria.

Loading...
> code result goes here
Prev
Next