Skip to content
Tutorials Center
My learning

Topics

Lesson 113 of 171 ยท Errors and Debugging

Custom Exception Classes

Learn to write custom exception classes in C++ - deriving from std::runtime_error, adding data, overriding what(), building hierarchies and nesting exceptions.

The standard library gives you a handful of ready-made exception types such as std::invalid_argument and std::out_of_range. They're fine for quick programs, but real applications need to say more. A configuration loader wants to report which line was broken. A payment service wants callers to tell "card declined" apart from "network down" without comparing message strings. The answer is your own exception classes: ordinary classes that you throw and catch by type.

In the Exceptions lesson you learned how throw, try and catch work. This lesson shows how to design the things you throw: which base class to derive from, how to carry extra data, how what() works, how to organize a small hierarchy so callers can catch broadly or narrowly, and how to wrap a low-level error inside a higher-level one with nested exceptions.

Why define your own exception types?

C++ lets you throw almost anything, even an int or a string literal. Please don't. A catch clause selects handlers by type, so the type is the most important piece of information an exception carries. Compare two ways of reporting the same problem:

C++
throw std::runtime_error("user 42 not found");   // callers must parse the text
throw UserNotFound(42);                          // callers catch UserNotFound and read .id()

The second version lets a caller write catch (const UserNotFound& e) and react to exactly that situation, while every other error keeps flowing up. It can also expose the user ID as an int, so nobody has to dig it out of a sentence that might be translated or reworded next month.

A good custom exception therefore does three things:

  • It has a specific type that names the failure.
  • It derives, directly or indirectly, from std::exception, so generic handlers like catch (const std::exception& e) still catch it.
  • It provides a readable message through what(), and any structured data through member functions.

Deriving from std::runtime_error

The easiest correct way to write an exception class is to derive from std::runtime_error (or one of its siblings, covered below) and inherit its constructors. std::runtime_error already stores the message and implements what(), so a one-line class is often enough.

C++ A minimal custom exception

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

using std::runtime_error::runtime_error; is an inheriting constructor declaration. It makes both base constructors, one taking const std::string& and one taking const char*, available on ConfigError. Without it you would write the constructor by hand:

C++
class ConfigError : public std::runtime_error {
public:
    explicit ConfigError(const std::string& message) : std::runtime_error(message) {}
};

Always catch your exceptions by const reference. Catching by value copies the object and slices off the derived part if you catch a base class; catching by pointer means someone must delete it.

Adding data to an exception

When a handler needs facts and not just text, store them as members and expose them with const getters. Build the human-readable message once, in the constructor, and pass it to the base class. That way what() stays cheap and can never fail.

C++ An exception that remembers where parsing failed

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Keep the extra members small and cheap to copy: integers, enums, a short code. An exception object may be copied while it propagates, and copying it should not throw. std::runtime_error stores its message in a reference-counted buffer, so copying the base part never throws, which is one more reason to put the text there instead of in your own std::string member.

Overriding what() yourself

Sometimes you want to derive straight from std::exception, for example when the message depends on data and you want full control. Then you override what(). Its exact signature matters:

C++
const char* what() const noexcept override;

It returns a C string, it's const, and it's noexcept: it must never throw. The pointer you return must stay valid as long as the exception object lives. The classic bug is returning the buffer of a temporary string:

C++
const char* what() const noexcept override {
    return ("HTTP error " + std::to_string(status_)).c_str();   // dangling pointer!
}

The temporary string is destroyed at the end of the return statement, so the caller receives a pointer into freed memory. That's undefined behavior. The fix is to build the message in the constructor and store it in a member.

C++ Overriding what() safely

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

In most code, deriving from std::runtime_error is simpler and just as good. Reach for a bare std::exception base only when you have a reason.

Choosing the right base class

The standard exceptions in <stdexcept> split into two families, and your classes should join the one that matches their meaning:

Base Meaning Standard examples
std::logic_error The caller broke a rule; a bug that better code could have avoided std::invalid_argument, std::out_of_range, std::length_error, std::domain_error
std::runtime_error Something outside the program's control went wrong std::range_error, std::overflow_error, std::system_error

A missing file, a refused connection or malformed user input is a runtime error. A negative index passed to your own container is a logic error. You can also derive from a more specific standard class: class BadColor : public std::invalid_argument says "this is an invalid argument, of a particular kind".

For errors reported by the operating system, the standard already has std::system_error, which carries a std::error_code. You'll meet it in Error Handling Without Exceptions.

Building an exception hierarchy

Larger programs usually define one base exception for the whole library or application, then derive specific types from it. Callers can choose their level of detail: catch one specific type, catch the whole family, or catch any std::exception.

C++ A small exception hierarchy

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

The output for scenario 3 is unexpected: std::bad_alloc, the text GCC's library returns from bad_alloc::what().

Handlers are tried top to bottom, and the first one that matches wins. If catch (const ShopError&) came first, it would also catch every OutOfStock, and the OutOfStock handler below it could never run. GCC warns about this ("exception of type 'OutOfStock' will be caught by earlier handler"). Order handlers from most derived to least derived.

A few rules keep hierarchies healthy:

  • Keep them shallow. Two or three levels are plenty. Add a type only when some caller will actually catch it separately.
  • Use public inheritance. With private or protected inheritance, a catch (const std::exception&) can't see the base and won't match.
  • Avoid multiple paths to std::exception. If a class inherits std::exception twice through two bases, the conversion is ambiguous and catch (const std::exception&) won't catch it.
  • Name types after what went wrong, not where: OutOfStock, not InventoryModuleException.

Nested exceptions

Often a low-level error has to be translated into a higher-level one. Say load_settings() fails because std::stoi threw. The caller should see "could not load settings.ini", but the original cause is valuable for logs. <exception> has two tools for this:

  • std::throw_with_nested(outer), called inside a catch block, throws an object that is both your outer exception and a holder of the exception currently being handled.
  • std::rethrow_if_nested(e) rethrows that inner exception if e has one, and does nothing otherwise.
C++ Wrapping a low-level error with throw_with_nested

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

The output shows the outer message first and the cause indented below it: could not load settings.ini, then stoi, which is the terse text libstdc++ uses for std::stoi failures. That terseness is exactly why wrapping helps: the outer layer adds context that the low-level function couldn't know.

Nested exceptions are handy at boundaries between layers, but don't wrap at every level. One wrapper where the meaning changes ("parse failure" becomes "settings failure") is usually enough.

Best practices

  • Derive from std::runtime_error or std::logic_error (or a more specific standard class) with public inheritance.
  • Inherit constructors with using Base::Base; when you add no data.
  • Build the message in the constructor; keep what() trivial and never let it throw.
  • Expose structured data through const noexcept getters, not by parsing what().
  • Throw by value (throw OutOfStock(...)), catch by const&, and order handlers from specific to general.
  • Don't use exceptions for ordinary control flow, like ending a loop. They're for situations where a function can't do its job.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Given class AppError : public std::runtime_error { public: using std::runtime_error::runtime_error; };, what does catch (const std::exception& e) do when AppError("boom") is thrown?

    AppError publicly derives from std::runtime_error, which derives from std::exception and stores the message passed to the constructor.
  2. 2. Why is returning (prefix + std::to_string(code)).c_str() from what() a bug?

    Lifetime extension applies to references bound to temporaries, not to pointers taken from them. Store the message in a member built by the constructor.
  3. 3. Handlers appear in the order catch (const ShopError&), then catch (const OutOfStock&). OutOfStock derives from ShopError. Which handler runs when OutOfStock is thrown?

    C++ picks the first matching handler, not the best one. Put the most derived types first.
  4. 4. What does std::rethrow_if_nested(e) do when e was not created by std::throw_with_nested?

    It only rethrows when e holds a nested exception, which is why the print_chain function stops cleanly at the innermost error.
  5. 5. A function receives a negative index for a container it owns. Which base class fits an exception for this best?

    logic_error describes mistakes the caller could have avoided. runtime_error is for conditions outside the program's control, such as missing files.

Summary

  • Custom exception types let callers catch exactly the failures they care about and read structured data instead of parsing messages.
  • Derive publicly from std::runtime_error or std::logic_error; using Base::Base; inherits the message constructors.
  • Build the message once in the constructor; what() is const noexcept and must return a pointer that outlives the call.
  • Organize related errors in a shallow hierarchy with one base per library, and order catch clauses from most to least derived.
  • std::throw_with_nested and std::rethrow_if_nested attach a low-level cause to a higher-level error.

Next: Exception Safety and noexcept, where you'll learn what your code promises when an exception flies through it.