0
0
CppConceptBeginner · 3 min read

What is std::exception in C++: Explanation and Example

std::exception is the base class for all standard exceptions in C++. It provides a common interface to catch and handle errors using the what() method that returns an error message.
⚙️

How It Works

Think of std::exception as a general safety net for errors in your C++ program. When something goes wrong, like trying to open a file that doesn't exist or dividing by zero, the program can "throw" an exception. This exception is like raising a flag that says "Hey, something unexpected happened!".

std::exception is the base class that all standard error types inherit from. It has a simple method called what() that returns a short message describing the error. Catching exceptions by this base class lets you handle many different errors in one place, like catching all kinds of problems with a single safety net.

💻

Example

This example shows how to catch a std::exception and print its message.

cpp
#include <iostream>
#include <exception>
#include <stdexcept>

int main() {
    try {
        throw std::runtime_error("Something went wrong!");
    } catch (const std::exception& e) {
        std::cout << "Caught exception: " << e.what() << std::endl;
    }
    return 0;
}
Output
Caught exception: Something went wrong!
🎯

When to Use

Use std::exception when you want to catch any standard error in your program without knowing the exact type. It is useful in large programs where many different errors can happen, and you want a simple way to handle them all.

For example, when working with files, network connections, or user input, many things can go wrong. Catching std::exception helps you show a friendly error message or safely stop the program instead of crashing.

Key Points

  • std::exception is the base class for standard exceptions.
  • The what() method returns a description of the error.
  • Catching by std::exception lets you handle many error types in one place.
  • Derived classes include std::runtime_error, std::logic_error, and others.

Key Takeaways

std::exception is the base class for all standard exceptions in C++.
Use the what() method to get a description of the error.
Catch exceptions by std::exception to handle multiple error types simply.
Derived exceptions provide more specific error information.
Handling exceptions prevents program crashes and improves reliability.