C++
Exception hierarchy
Learn the exception hierarchy and custom exceptions.
Exception hierarchy
In C++ all exceptions derive from std::exception. The <stdexcept> header offers two main branches: std::logic_error (programmer mistake) and std::runtime_error (runtime condition).
From std::logic_error derive: std::invalid_argument, std::out_of_range, std::length_error. From std::runtime_error derive: std::overflow_error, std::underflow_error, std::system_error. Thanks to this hierarchy, a single catch (const std::exception&) can catch all exceptions. Each exception returns a message through its what() member.
Custom exception class
You write your own exception class by deriving from std::exception. You redefine the what() member with override.
Example: class InvalidScore : public std::exception { public: const char* what() const noexcept override { return "negative score"; } };. what() is both const and noexcept; this is for compatibility with the base class. You can then throw it with throw InvalidScore{}; and catch it with catch (const std::exception& e). The message is read with e.what().
Exercise Write a custom exception class
Derive InvalidScore from std::exception. Its what() member should be const noexcept override and return "negatif skor". In main throw it with throw InvalidScore{} and catch it with catch (const std::exception& e), printing e.what().
Show example solution
#include <iostream>
#include <exception>
class InvalidScore : public std::exception {
public:
const char* what() const noexcept override {
return "negatif skor";
}
};
int main() {
try {
throw InvalidScore{};
} catch (const std::exception& e) {
std::cout << e.what();
}
return 0;
}
Test yourself
-
Which one derives from std::logic_error?
- std::out_of_range
- std::overflow_error
- std::runtime_error
- std::bad_alloc
Show answer
std::out_of_range — std::out_of_range derives from std::logic_error; it is a programmer mistake.
-
derive from std::exception
class InvalidScore : public ____ { };
Show answer
class InvalidScore : public std::exception { };
-
Match each class to its description
- std::exception
- Base class
- std::logic_error
- Programmer mistake
- std::runtime_error
- Runtime condition
- std::out_of_range
- Out of bounds access
Next lesson: Exception safety