For my current project I am regularly defining custom exceptions that I want to catch.
However, I am struggling with deciding what the best structure is for my code regarding the definition of these exceptions.
Initially, I just defined the exceptions nested inside my classes that throw them, like so:
class Foo {
struct CustomException : public std::runtime_error {
}
void TrySomething() {
throw CustomException();
}
};
However, now I am using template classes, I cannot access this exception without providing a template argument. That is, I cannot do:
template class <T>
class Foo {
struct CustomException : public std::runtime_error {
}
void TrySomething() {
throw CustomException();
}
};
void SomeFunction() {
try {
Foo foo;
foo.TrySomething();
}
catch (const Foo::CustomException& exc) {
}
}
Because Foo without a template argument is not a class. I'm trying to figure out what the cleanest solution to this is (with the option of reworking the rest of the project to follow the chosen standard).
Options that come in mind:
- Make an interface for Foo and put the exception class in there (this seems a bit excessive, making an interface just for this reason)
- Put the exception in a namespace I have made for Foo specifically
- Put the exception 'free' around Foo (but I am guessing in a project namespace, which I don't have for my project right now, but I have read is good practise anyway)
- Put all exceptions in a single file, in a namespace or struct
- Make one 'Exceptions' namespace, and extend this whenever I want to add one (in the class file that throws the exception)