由于finally在C++中没有,你必须使用RAII设计模式,如果你希望你的代码是异常安全的.一种方法是使用像这样的本地类的析构函数:
void foo() {
struct Finally {
~Finally() { /* cleanup code */ }
} finalizer();
// ...code that might throw an exception...
}
Run Code Online (Sandbox Code Playgroud)
与直接解决方案相比,这是一个很大的优势,因为您不必编写清理代码2次:
try {
// ...code that might throw an exception...
// cleanup code (no exception)
} catch (...) {
// cleanup code (exception)
throw;
}
Run Code Online (Sandbox Code Playgroud)
本地类解决方案的一大缺点是您无法直接访问清理代码中的局部变量.因此,如果您需要访问它们,它会使您的代码膨胀很多,无论如何:
void foo() {
Task* task;
while (task = nextTask()) {
task->status = running;
struct Finally {
Task* task;
Finally(Task* task) : task(task) {}
~Finally() { task->status …Run Code Online (Sandbox Code Playgroud) 如何在不必将字符串硬编码到应用程序中的情况下获得SEH异常的名称和/或描述?
我尝试使用FormatMessage(),但它有时会截断消息,即使您指定忽略插入:
__asm { // raise access violation
xor eax, eax
mov eax, [eax]
}
Run Code Online (Sandbox Code Playgroud)
使用代码引发异常0xC0000005 (EXCEPTION_ACCESS_VIOLATION).
char msg[256];
FormatMessageA(FORMAT_MESSAGE_FROM_HMODULE | FORMAT_MESSAGE_IGNORE_INSERTS,
GetModuleHandleA("ntdll.dll"), 0xC0000005,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
msg, sizeof(msg), NULL);
Run Code Online (Sandbox Code Playgroud)
填充msg截断的字符串:" The instruction at 0x".