0

When compiler meets an exception that is from STL like std::out_of_range :

int main(int argc, char *argv[]) {
    throw std::out_of_range("There is an exception!");
}

the console will show the message :

libc++abi.dylib: terminating with uncaught exception of type std::out_of_range: There is an exception!

So I wrote an exception class :

class Exception {
    protected:
        const char *msg;
    public:
        Exception(const char *msg) noexcept : msg(msg) {}
        Exception(const string &msg) noexcept : msg(msg.c_str()) {}
        const char *what() const noexcept {
            return this->msg;
        }
};

However, throwing Exception will not get any information :

int main(int argc, char *argv[]) {
    throw Exception("There is an exception!");
}

Console message :

libc++abi.dylib: terminating with uncaught exception of type Exception

Is there any way making console show :

libc++abi.dylib: terminating with uncaught exception of type Exception: There is an exception!

Compiler : Apple LLVM version 9.1.0 (clang-902.0.39.2)

Jonny0201
  • 433
  • 5
  • 10
  • 5
    What happens if you inherit from `std::exception`? – NathanOliver Jun 27 '18 at 12:44
  • 3
    What is the reason to reimplement your own exception hierarchy? What's wrong with the standard C++ exceptions? Why can't you inherit from them? What is the *real* problem you want to solve using non-standard exceptions? – Some programmer dude Jun 27 '18 at 12:45
  • Possible duplicate of [Creating custom exceptions in C++](https://stackoverflow.com/questions/41753358/creating-custom-exceptions-in-c) – Qubit Jun 27 '18 at 12:45
  • 6
    Your `Exception(const string &)` constructor is very likely to store a pointer which becomes invalid when stack unwinding destroys the original `std::string` object. – aschepler Jun 27 '18 at 12:49
  • 5
    If you want to control what happens when an exception is thrown, **catch it**. The language definition doesn't require any sort of display for an uncaught exception. – Pete Becker Jun 27 '18 at 12:54

1 Answers1

0

If you derive your exception class publicly from std::exception then the compiler provided exception handler will be able to print more information for your exception.

Maxim Egorushkin
  • 131,725
  • 17
  • 180
  • 271