Exception hierarchy
- C++ course
- Advanced
- Lesson 73/83
- 5 min
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().
Practice 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().
Starter code
#include <iostream>
#include <exception>
// Derive InvalidScore from std::exception
int main() {
// Throw it and catch it
return 0;
}Sample 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;
}Expected output
negatif skor
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which one derives from std::logic_error?
- std::out_of_range Correct answer
- std::overflow_error
- std::runtime_error
- std::bad_alloc
Explanation: std::out_of_range derives from std::logic_error; it is a programmer mistake.
2 derive from std::exception
class InvalidScore : public ____ { };
class InvalidScore : public std::exception { };
Explanation: Custom exceptions derive from std::exception.
3 Match each class to its description
| Term | Meaning |
|---|---|
std::exception |
Base class |
std::logic_error |
Programmer mistake |
std::runtime_error |
Runtime condition |
std::out_of_range |
Out of bounds access |