c++怎么在try{}catch(...){}中得到代码停止执行的位置(行号)?
时间: 2023-11-27 15:53:35 浏览: 43
在C++中,可以使用`__LINE__`和`__FILE__`宏来获取代码行号和文件名。在`catch(...)`块中,你可以使用`std::exception_ptr`来保存当前发生的异常,然后在捕获到异常时使用`std::current_exception()`来获取异常指针。然后通过`std::exception_ptr`的`what()`方法获取异常信息,并使用`__LINE__`和`__FILE__`宏来获取当前的代码行号和文件名。
以下是一个示例代码:
```c++
#include <iostream>
#include <exception>
#include <string>
int main() {
try {
int a = 10;
int b = 0;
int c = a / b;
}
catch (...) {
std::exception_ptr p = std::current_exception();
try {
if (p) {
std::rethrow_exception(p);
}
}
catch (const std::exception& e) {
std::cerr << "Exception caught at " << __FILE__ << ":" << __LINE__ << std::endl;
std::cerr << e.what() << std::endl;
}
}
return 0;
}
```
在上面的示例中,由于除数为0,会抛出一个`std::exception`异常,并在`catch(...)`块中捕获。然后使用`std::current_exception()`获取异常指针,并在内部`try-catch`块中调用`std::rethrow_exception()`重新引发异常。最后,在`catch(const std::exception& e)`块中获取异常信息并输出行号和文件名。