搜尋此網誌

2026年1月27日星期二

Exception handling in C++

Exception handling in C++ is a structured way to detect and manage runtime errors using try, catch, and throw keywords, allowing programs to recover gracefully instead of crashing. It helps deal with issues like division by zero, invalid memory access, or file (input and output) I/O failures.

try block

    Contains code that might generate an exception.

    Example: risky operations like division or file handling.

throw keyword

    Used to signal that an error has occurred.

    Example: throw "File not found";

catch block

    Defines how to handle the exception.

    Example: catch (const char* msg) { cout << msg; }


#include <iostream>

using namespace std;


int main() {

    try {

        int x = 10, y = 0;

        if (y == 0) {

            throw runtime_error("Division by zero error!");

        }

        cout << x / y;

    }

    catch (runtime_error &e) {

        cout << "Exception caught: " << e.what() << endl;

    }

    return 0;

}


Output:
Exception caught: Division by zero error!


In C++, the e.what() method is used with exceptions that are derived from the standard exception class std::exception.

What it does

  • std::exception defines a virtual function what() that returns a C-style string (const char*) describing the error.
  • When you catch an exception object (like std::runtime_error, std::out_of_range, etc.), calling e.what() gives you a human-readable message about what went wrong.


In C++, array index out-of-bounds occurs when you try to access an element outside the valid range of an array.

In C++, the symbol || is the logical OR operator.

    It evaluates two boolean expressions (conditions).

    The result is true if at least one of the conditions is true.

    The result is false only if both conditions are false.


Always catch exceptions by reference (usually const &) to:

    Avoid object slicing.

    Preserve polymorphic behavior (what() works correctly for derived classes).

    Improve performance (no extra copy).


Microsoft Copilot

沒有留言:

發佈留言