My code right now looks something like this:
void throw_illegal_part_of_input_exception(char c) {}
void throw_invalid_input_length_exception(int position, int length) {}
void throw_invalid_subinput_length_exception(int position, int length, bool is_greater) {}
// Some other similar functions
// ... do some stuff inside a function
if (errorCondition1) {
throw_invalid_character_exception(c);
} else if (errorCondition2) {
throw_invalid_input_length_exception(position, length);
} // etcetera
The content of the functions is largely the same; however, the error messages I want to use in the thrown exceptions are very different and depend on the arguments. Is there a better way to write this?
2
There is no real best way. There are some options:
- Create an exception hierarchy with a class for each specific exception that all inherit from a common base class (the exception class you are using now for example). Each specific exception class then carries the details of the encountered error and can produce a human-readable message when the
what()
method gets called.
This option is particularly useful if you might want to differentiate between the different exceptions in your catch clauses. - Use a single exception type that gets filled with different messages at the throw point.
This is your current approach and is perfectly valid if you know beforehand that the calling code will never have a need to differentiate between the different kinds of errors.
If there is no need to have different exception types, then it comes down mostly to personal preference and agreements within the team which option to use. We can’t advise in that.
Looks like classic polymorphism. Could you create an exception object that you can inherit variations like this from?
Whats wrong with:
// ... do some stuff inside a function
if (errorCondition1) {
sprintf(gmsg,"Invalid character %c at %d",echar,epos)
throw_general_exception(gmsg);
} else if (errorCondition2) {
sprintf(gmsg,"Wrong length record position %d length %d",position,length)
throw_general_exception(gmsg);
} // etcetera
Unless you want to handle one of the errors in a completely different way having specific exceptions for each possible error is just lots of work for little reward.
1
You’re making this too complicated. Just throw an InputValidationException
, and find a way for the exception to carry some additional information (this could be as simple as an error message), so that you can identify the input validation error specifically.
1