遇到不是来自STL的未捕获异常时,有什么方法可以打印其信息?

时间:2018-06-27 12:41:54

标签: c++ c++11

当编译器遇到来自std::out_of_range之类的STL的异常时:

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

控制台将显示消息:

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

所以我写了一个异常类:

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;
        }
};

但是,抛出Exception不会得到任何信息:

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

控制台消息:

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

有什么方法可以使控制台显示出来:

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

编译器:Apple LLVM version 9.1.0 (clang-902.0.39.2)

1 个答案:

答案 0 :(得分:0)

如果从std::exception公开派生异常类,则编译器提供的异常处理程序将能够为您的异常打印更多信息。