Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best practices for defining your own exception classes?

I have some special exception cases that I want to throw and catch, so I want to define my own exception classes.

What are the best practices for that? Should I inherit from std::exception or std::runtime_error?

like image 934
Frank Avatar asked Mar 27 '09 03:03

Frank


People also ask

What must you provide If you define your own exception class?

If you decide to define your own exception class. it must be a subclass of a Throwable class. You must decide which class you will extend. The two existing subclasses of Throwable are Exception and Error.

Can you write your own custom exception class?

To create a custom exception, we have to extend the java. lang. Exception class. Note that we also have to provide a constructor that takes a String as the error message and called the parent class constructor.


2 Answers

Yes, it's good practice to inherit from std::runtime_error or the other standard exception classes like std::logic_error, std::invalid_argument and so on, depending on which kind of exception it is.

If all the exceptions inherit some way from std::exception it's easy to catch all common errors by a catch(const std::exception &e) {...}. If you have several independent hierarchies this gets more complicated. Deriving from the specialized exception classes makes these exceptions carry more information, but how useful this really is depends on how you do your exception handling.

like image 71
sth Avatar answered Oct 14 '22 19:10

sth


I'm not a C++ developer, but one thing we did in our C# code was create a base class exception for our framework, and then log the exception thrown in the constructor:

  public FrameworkException(string message, Exception innerException)       : base(message, innerException)   {       log.Error(message, innerException);   }    ... 

Any derived exception just has to invoke it's base constructor and we get consistent exception logging throughout. Not a big deal, but useful.

like image 42
si618 Avatar answered Oct 14 '22 21:10

si618