0

I am developing a header-only C++20 library, and now I need to add exception classes.
And I have two choices:

  1. 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 {
    // ...
};

// ...
  1. 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?

2
  • The second is a nice way to circumvent type system. Commented Oct 3, 2022 at 8:31
  • 1
    Depends on what kind of information you need to extract from a exeception. If basically everything you do is passing on error codes, different exception types not required and can just mean you need to write more exeception classes for no benefit. If you often need to handle different types of errors differently, you should be using separate exception classes. Note that you can easily combine both by having the library_error class constructor take an error code which would allow you to both catch the exception as library_error const& and catch more specific exception types. Commented Oct 3, 2022 at 8:38

1 Answer 1

1

Likely, an exception is not only thrown blank, but there are arguments to it. E.g. the file missing, the device on which the playing error occurred. You'd likely expect the exception handler to be able to process these. Therefore, I'd strongly suggest not to go around the type system and have an exception type hierarchy.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.