无法看到引发异常的代码行
Unable to see the code line throwing an exception
当我使用具有优化级别o3
的g++
编译代码,然后使用lldb
进行调试直到发生崩溃时,没有代码行在回溯中引发异常。我不想使用-g
标志,因为我的源代码不必在生产中可见。
让我们考虑一个简单的案例:
测试.cpp
int main() {
bool isOdd = std::rand() & 1;
if (isOdd) {
throw std::logic_error("An exception for the odd number was thrown!");
} else {
throw std::logic_error("An exception for the even number was thrown!");
}
}
然后我编译它
g++ -o3 -std=c++14 -o test.o test.cpp
并使用以下一组命令查看回溯跟踪:
lldb test.o
r
bt
但是回溯跟踪并没有真正的帮助,因为它不包含抛出异常的代码行或传递给logic_error
的字符串消息("An exception for the odd number was thrown!"
或"An exception for the even number was thrown!"
(:
...
frame #7: 0x00007fff5011f26f libc++abi.dylib`__cxa_throw + 121
frame #8: 0x0000000100000e11 test.o`main + 113
frame #9: 0x00007fff5215d015 libdyld.dylib`start + 1
...
有没有办法在不使用任何外部库的情况下克服此限制?
我使用MacOS
和g++
作为编译器,LLDB
作为调试工具。
一种方法是使用可变参数模板函数来重新引发给定的异常。模板参数包括id
参数和异常参数。id
是唯一编号,将用于标识引发异常的代码行。参数用于创建和重新引发异常。因此,代码可能如下所示:
template<uint32_t id, class... Arguments>
void rethrow(Arguments&&... args) {
std::rethrow_exception(std::make_exception_ptr(std::logic_error(std::forward<Arguments>(args)...)));
}
int main() {
bool isOdd = std::rand() & 1;
if (isOdd) {
rethrow<1>("An exception for the odd numbers!");
} else {
rethrow<2>("An exception for the even numbers!");
}
}
在我重新编译代码并检查回溯跟踪后,在我的情况下id = 1
:
frame #9: 0x0000000100000c65 test.o`void rethrow<1u, char const (&) [34]>(char const (&&&) [34]) + 69
因此,从
rethrow<1>("An exception for the odd numbers!");
相关文章:
- 我在c++代码中生成了一个运行时#3异常
- 孤立代码块在结构中引发异常
- 是否值得降低我的代码的可读性,以便在出现内存不足错误时提供异常安全性?
- VisualStudios 会抛出异常,而代码块不会 [C++]
- [longjmp/setjmp]c++ 相同的代码窗口有异常 Linux 没有错误并且运行良好
- 为什么代码段会引发浮点异常?
- 我应该C++自定义异常代码放在哪里?
- WinDBG适用于从Visual Studio 2015保存的转储,但不适用于任务管理器。显示异常代码"not found"
- C++中的奇怪异常代码,当用户输入为 23 时,退出值 1,073,740,940(代码:0xc0000374)
- 如何在Visual Studio(2015)中增加堆栈尺寸的堆栈尺寸?异常代码:C00000FD
- 从覆盖范围报告中删除自动生成的异常代码
- 防火墙异常代码仅适用于传出连接
- 需要对异常代码进行解释
- C/C++语言-指针和算术..异常代码:c0000005
- 异常代码"EXC_I386_GPFLT"的含义是什么?
- 单元测试失败,异常代码为c0000005
- 如何使异常代码DRY
- 访问计算机指针时发生访问冲突(c系统异常代码:c0000005),导致应用程序崩溃
- 如何在Windows上诊断异常代码0xc0000409
- 如何在iOS Objective-C中捕获C++异常代码