cpp-que-son-excepciones

What are and how to use exceptions in C++

  • 3 min

An exception in C++ is a mechanism that allows handling errors or unexpected situations during program execution.

When an exception occurs:

  • It can be caught by a try-catch block
  • If it is not caught, it passes to the function that called the one that generated the error

If there is no try-catch block to catch the exception, it “goes up”. If no one handles it, the exception will reach the main function (normally the program terminates abruptly).

Exceptions in C++ are thrown using objects, which can be of any type, although it is common to throw objects of specific types (like std::runtime_error or std::logic_error).

Throwing an exception

In C++, we can throw an exception using the throw keyword. This allows us to indicate that a specific error has occurred.

#include <stdexcept>

throw std::runtime_error("An error occurred");
Copied!

In this example, we throw an exception of type std::runtime_error with an error message.

This message can later be used in the catch block to identify and handle the error.

Predefined exceptions

In C++, there are several predefined exception types in the standard library that allow handling common errors. Here are some examples:

These are just some of the common exceptions in C++. The standard library includes more specific exceptions for various situations.

Creating custom exceptions in C++

In C++ it is also possible to define custom exceptions by creating classes that inherit from an exception base class, such as std::exception.

#include <exception>
#include <string>

class MyException : public std::exception {
    std::string message;
public:
    explicit MyException(const std::string& message) : message(message) {}
    const char* what() const noexcept override {
        return message.c_str();
    }
};
Copied!

Here, MyException inherits from std::exception and overrides the what() method to provide a custom error message.

Using a custom exception

We can use our custom exception class in a try-catch block like any other exception:

#include <iostream>

int main() {
    try {
        throw MyException("Error in my custom application");
    } catch (const MyException& e) {
        std::cout << "Custom exception caught: " << e.what() << std::endl;
    }
    return 0;
}
Copied!

In this case, the error message of MyException will be printed to the console.