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 중국어 웹사이트의 기타 관련 기사를 참조하세요!