So I know that an exception class can inherit from the std exception library, but what exactly does an exception class do? It throws exceptions and handles them, but why should I use a class? Can an exception class handle more than 1 type of object?
-
5An exception class doesn't throw exceptions. You throw an instance of an exception class. It holds data about the exception that you can retrieve later. They also don't handle exceptions. You catch those, too.Qaz– Qaz2014-08-12 19:10:26 +00:00Commented Aug 12, 2014 at 19:10
-
It's an exception, an anomaly, an error, an unexpected thing. It doesn't do anything, it just is. It's a class because classes are what we use to store information, and the details about the exception must be stored somewhere.molbdnilo– molbdnilo2014-08-12 19:14:34 +00:00Commented Aug 12, 2014 at 19:14
-
Exception classes are not the only throwable things, everything can be thrown (like an int, float, char *, std::string, ...).Kapichu– Kapichu2014-08-12 19:16:42 +00:00Commented Aug 12, 2014 at 19:16
Add a comment
|
1 Answer
There is no such thing as an "exception class" in C++; there are
no constraints with regards to the type of what you can throw
and catch. (throw 3.14159; is a perfectly legal C++
statement.) Good programming practice says that except in
special cases, you should throw objects which inherit from
std::exception, but this is not a requirement, and it's not
unusual for programs to throw an int to trigger the end of
program. (Calling exit doesn't invoke all of the destructors,
so the program throws an int, which is caught and returned in
main.)