Josh
Josh

Reputation: 6272

Proper use of exceptions in C++

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?

Upvotes: 5

Views: 1356

Answers (4)

jhoffmann
jhoffmann

Reputation: 31

I would subclass std::exception() for your invalid_input class in the example you gave. Typically, a user input error is not considered a runtime error, you may want to catch it earlier, you may want to perform different logic when it occurs. Using or subclassing in this case from runtime_exception in most cases fails the "is a" test.

Upvotes: 1

AwDogsGo2Heaven
AwDogsGo2Heaven

Reputation: 972

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()

Upvotes: 1

suszterpatt
suszterpatt

Reputation: 8273

I would only subclass a standard exception class in one of two cases:

  1. None of the standard exception classes have names that describe the nature of my exception
  2. My exception needs additional information than what can be found in a standard exception (i.e. a string describing the error).

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.

Upvotes: 7

Barış Uşaklı
Barış Uşaklı

Reputation: 13532

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.

Upvotes: 1

Related Questions