I am developing a header-only C++20 library, and now I need to add exception classes.
And I have two choices:
- One base class and many subclasses
class library_error : public std::exception {
// ... other work
};
class parse_error : public library_error {
// ...
};
class playing_error : public library_error {
// ...
};
class bad_attr : public library_error {
// ...
};
// ...
- One exception class based on error codec, a errc and a category
class library_error : public std::exception {
// ...
public:
const std::error_code& code() const noexcept;
};
enum class library_errc {
parse_error = 0xbadbad,
playing_error = 0x9ood9ood,
bad_attr = 0x123456,
// ...
};
class library_erorr_category : public std::error_category {
// ...
};
This library has a lot of detailed exception types. Which is better? Or is there any better solution?
library_errorclass constructor take an error code which would allow you to both catch the exception aslibrary_error const&and catch more specific exception types.