Identifying the Exact Source of Unhandled Exceptions
It is often desirable to determine the specific line of code that caused an exception, even if it was not explicitly generated by the programmer.
Custom Exception Class and Macro
A recommended approach involves creating a custom exception class and a corresponding macro. For example:
class my_exception : public std::runtime_error { std::string msg; public: my_exception(const std::string &arg, const char *file, int line) : std::runtime_error(arg) { std::ostringstream o; o << file << ":" << line << ": " << arg; msg = o.str(); } ~my_exception() throw() {} const char *what() const throw() { return msg.c_str(); } }; #define throw_line(arg) throw my_exception(arg, __FILE__, __LINE__);
Usage:
The my_exception class constructs customized exception messages that include the file name, line number, and user-defined error message. The throw_line macro is used to generate custom exceptions with these enhanced error messages.
In the following example, the throw_line macro is used within function f:
void f() { throw_line("Oh no!"); }
When f throws the exception, the main function catches it and prints the customized error message to the console:
int main() { try { f(); } catch (const std::runtime_error &ex) { std::cout << ex.what() << std::endl; } }
This approach provides a convenient mechanism for generating exceptions with detailed information about their origin, regardless of whether they were generated explicitly or not.
以上是如何查明未處理異常的確切來源?的詳細內容。更多資訊請關注PHP中文網其他相關文章!