当遇到不是来自 STL 的未捕获异常时,有没有办法打印其信息?

Is there any way to print its information when met an uncaught exception that is not from STL?

本文关键字:有没有 打印 信息 捕获异常 遇到 STL      更新时间:2023-10-16

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

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)

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