graywolf
graywolf

Reputation: 7480

How much classes for exceptions

What's the usual way to create & handle exceptions in c++?

class CannotRead : public runtime_exception { ... }
class CannotParse : public runtime_exception { ... }

...
throw CannotRead();
...

or

...
throw runtime_error("cannot read");
...

What's the idiomatic way to do this in C++?

Links to articles comparing both approaches would be appreciated.

Thanks

Upvotes: 1

Views: 87

Answers (2)

Tyler Jandreau
Tyler Jandreau

Reputation: 4335

Typically, as others have mentioned in comments, you derive from std::runtime_error and overload the what() virtual method. As an exercise to the reader, a constructor can also be written to capture the exception message. This website provided the following code (although I modified it slightly to reflect the std::runtime_error change).

#include <iostream>
#include <exception>

class MyException : public std::runtime_error
{       
    const char * what () const throw () { 
        return "C++ Exception";
    }
};

int main()
{
    try {
        throw MyException();
    } catch(MyException& e) {
        std::cout << "MyException caught" << std::endl;
        std::cout << e.what() << std::endl;
    } catch(std::exception& e) {
    }

    return 0;
}

Upvotes: 1

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385104

There's no cut and dry advice to give, but my personal rule of thumb is:

  • throw std::runtime_error (or one of its siblings, as appropriate)
  • until you find you need to distinguish at catch-time between your various exceptions, then start deepening the inheritance heirarchy.

Upvotes: 4

Related Questions