0
0
C++programming~5 mins

Why exception handling is required in C++

Choose your learning style9 modes available
Introduction

Exception handling helps your program deal with unexpected problems without crashing. It lets you catch errors and fix them or show a friendly message.

When reading a file that might not exist.
When dividing numbers and the divisor could be zero.
When connecting to a network that might be down.
When converting user input to a number that might be invalid.
Syntax
C++
try {
    // code that might cause an error
} catch (const std::exception& e) {
    // code to handle the error
}
Use try to wrap code that might fail.
Use catch to handle the error and keep the program running.
Examples
This catches a standard exception and prints the error message.
C++
try {
    std::stoi("abc");
} catch (const std::exception& e) {
    std::cout << "Error: " << e.what() << std::endl;
}
This throws and catches a runtime error with a custom message.
C++
try {
    throw std::runtime_error("Something went wrong");
} catch (const std::runtime_error& e) {
    std::cout << e.what() << std::endl;
}
Sample Program

This program tries to divide by zero. Instead of crashing, it catches the error and prints a message. Then it continues running.

C++
#include <iostream>
#include <stdexcept>

int main() {
    try {
        int x = 10;
        int y = 0;
        if (y == 0) {
            throw std::runtime_error("Division by zero is not allowed");
        }
        int z = x / y;
        std::cout << "Result: " << z << std::endl;
    } catch (const std::runtime_error& e) {
        std::cout << "Caught an error: " << e.what() << std::endl;
    }
    std::cout << "Program continues after handling the error." << std::endl;
    return 0;
}
OutputSuccess
Important Notes

Without exception handling, the program would stop immediately on errors.

Exception handling makes programs more reliable and user-friendly.

Summary

Exception handling helps catch and manage errors gracefully.

It prevents program crashes and allows recovery or user messages.

Use try and catch blocks to handle exceptions.