In C++ should I use std::runtime_error
to indicate some sort of error occurred, or should I create custom exceptions that inherit from std::runtime_error
so I can better handle them.
For example, if I got input from the user somehow, which would be better:
if (inputInvalid)
{
throw std::runtime_error("Invalid input!");
}
Versus...
class invalid_input
: public std::runtime_error /* or should I inherit from std::exception? */
{
public:
invalid_input()
: std::runtime_error("Invalid input!")
{
};
};
-------------------------------------------------------
if (inputInvalid)
{
throw invalid_input();
}
Which is considered better use of exception handling/which if better practice?
I would only subclass a standard exception class in one of two cases:
Otherwise, there's not much point. Especially if others will have to interact with your code and wonder why there is a custom exception class that doesn't do anything a standard exception doesn't.
Always think about what you gain from inheriting std::runtime_error. Does it let you handle the error easier? In the example code it doesn't give any benefits so no there is no point in inheriting from std::runtime_error if all it does is the same thing. If you want to add more information than what std::runtime_error has then you might want to inherit and add those to your error class.
That will depend on the size of the project. If your working on something small and just need something quick and dirty, std:runtime_error is fine. But if your working on a big project you are going to want to create your own custom exceptions to help manage(through catches) all the different possibilities. Otherwise now if you made a catch, you would be catching EVERYTHING, which may be a problem if you need to catch multiple different things with different ways to handle them.
I would also read this:
Difference: std::runtime_error vs std::exception()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With