Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 322
Josh Avatar asked Apr 26 '12 15:04

Josh


3 Answers

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.

like image 57
suszterpatt Avatar answered Nov 03 '22 05:11

suszterpatt


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.

like image 39
Barış Uşaklı Avatar answered Nov 03 '22 05:11

Barış Uşaklı


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

like image 27
AwDogsGo2Heaven Avatar answered Nov 03 '22 05:11

AwDogsGo2Heaven