Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I inherit from std::exception?

I've seen at least one reliable source (a C++ class I took) recommend that application-specific exception classes in C++ should inherit from std::exception. I'm not clear on the benefits of this approach.

In C# the reasons for inheriting from ApplicationException are clear: you get a handful of useful methods, properties and constructors and just have to add or override what you need. With std::exception it seems that all you get is a what() method to override, which you could just as well create yourself.

So what are the benefits, if any, of using std::exception as a base class for my application-specific exception class? Are there any good reasons not to inherit from std::exception?

like image 387
John M Gant Avatar asked Nov 03 '09 19:11

John M Gant


People also ask

Can you inherit an STD?

Some STIs, such as syphilis, cross the placenta and infect the baby in the womb. Other STIs, like gonorrhea, chlamydia, hepatitis B, and genital herpes, can pass from the mother to the baby as the baby passes through the birth canal.

What is std :: exception in C++?

std::exceptionBase class for standard exceptions. All objects thrown by components of the standard library are derived from this class. Therefore, all standard exceptions can be caught by catching this type by reference. It is declared as: C++98.

Which is the parent class for all exceptions STD?

All exceptions are derived from std::exception class. It is a runtime error which can be handled. It prints exception message and terminates the program, if we don't handle the exception. This is an exception and parent class of all the standard C++ exceptions.

How do you catch errors in C++?

Exception handling in C++ is done using three keywords: try , catch and throw . To catch exceptions, a portion of code is placed under exception inspection. This is done by enclosing this portion of code in a try block. When an exception occurs within the try block, control is transferred to the exception handler.


1 Answers

The main benefit is that code using your classes doesn't have to know exact type of what you throw at it, but can just catch the std::exception.

Edit: as Martin and others noted, you actually want to derive from one of the sub-classes of std::exception declared in <stdexcept> header.

like image 128
Nikolai Fetissov Avatar answered Sep 30 '22 20:09

Nikolai Fetissov