Home > Software engineering >  C Exception codes vs classes
C Exception codes vs classes

Time:10-04

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?

CodePudding user response:

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.

  • Related