C++、__try 和 try/catch/finally

时间:2023-03-08
本文介绍了C++、__try 和 try/catch/finally的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我有点想知道 C++ try/catch/finally 块.我见过这些带有两个下划线的命令,比如 __try.但是 MVSC 2010 项目也没有下划线运行.那么什么时候需要这些下划线?

I'm wondering a bit about C++ try/catch/finally blocks. I've seen these commands with two underscores like __try. But MVSC 2010 projects also run without the underscores. So when do you need these underscores?

推荐答案

在 Windows 上,在操作系统级别支持异常.称为结构化异常处理 (SEH),它们大致相当于 Unix 信号.为 Windows 生成代码的编译器通常利用这一点,它们使用 SEH 基础结构来实现 C++ 异常.

On Windows, exceptions are supported at the operating system level. Called Structured Exception Handling (SEH), they are the rough equivalent to Unix signals. Compilers that generate code for Windows typically take advantage of this, they use the SEH infrastructure to implement C++ exceptions.

为了与 C++ 标准保持一致,throwcatch 关键字只抛出和捕获 C++ 异常.MSVC编译器对应的SEH异常代码是0xe06d7363.最后 3 个字节是msc"的 ASCII 码.

In keeping with the C++ standard, the throw and catch keywords only ever throw and catch C++ exceptions. The corresponding SEH exception code for the MSVC compiler is 0xe06d7363. The last 3 bytes are the ASCII code for "msc".

将它与操作系统支持统一也意味着 C++ 析构函数将在堆栈展开期间为 SEH 异常调用.执行展开的代码在 Windows 内部,并以与任何 SEH 完全相同的方式处理由 throw 引发的 SEH.但是,Microsoft 编译器进行了优化,尝试避免生成确保在所有情况下都调用析构函数所需的代码.如果它可以证明在控制对象生命周期的范围块中没有 throw 语句,那么它会跳过注册代码.这与异步 SEH 异常不兼容,如果您打算捕获 SEH 异常,则应使用/EHa 编译选项来抑制此优化.

Unifying it with the operating system support also means that C++ destructors will be called during stack unwinding for an SEH exception. The code that does the unwinding is inside Windows and treats the SEH raised by a throw the exact same way as any SEH. However, the Microsoft compiler has an optimization that tries to avoid generating the code required that ensures that destructors are called in all cases. If it can prove that there's no throw statement inside the scope block that controls the object's lifetime then it skips the registration code. This is not compatible with asynchronous SEH exceptions, you should use the /EHa compile option to suppress this optimization if you intend to catch SEH exceptions.

有很多 SEH 异常类型.操作系统可以生成的在ntstatus.h SDK头文件中列出.此外,您可能会与使用 SEH 实现自己的异常处理的代码互操作,他们将使用自己的异常代码.与 .NET 一样,托管异常使用 0xe0434f4d(com")异常代码.

There are a lot of SEH exception types. The ones that can be generated by the operating system are listed in the ntstatus.h SDK header file. In addition, you might interop with code that uses SEH to implement their own exception handling, they will use their own exception code. Like .NET, managed exceptions use the 0xe0434f4d ("com") exception code.

要在 C++ 程序中捕获 SEH 异常,您必须使用非标准的 __try 关键字.__except 关键字类似于 C++ catch 关键字.它具有更多功能,您可以指定一个异常过滤器表达式来确定是否应捕获活动异常.一切皆有可能,但您通常只查看传递的异常信息,看看您是否有兴趣处理它.__finally 关键字允许您编写在处理异常后运行的代码.在 C++ 中没有等价物,但在其他语言中并不少见.

To catch SEH exceptions in a C++ program, you must use the non-standard __try keyword. The __except keyword is analogous to the C++ catch keyword. It has more capabilities, you specify an exception filter expression that determines whether or not an active exception should be caught. Anything is possible, but you typically only look at the passed exception information to see if you're interested in handling it. The __finally keyword lets you write code that runs after the exception is handled. No equivalent for that in C++ but not uncommon in other languages.

正如评论中指出的那样,所有这些都没有很好的记录.证据就在布丁里.这是您可以使用的示例程序.它演示了 SEH 异常如何仍然允许调用 C++ 析构函数,前提是您使用/EHa 进行编译以及如何在 SEH 之上实现 C++ 异常.需要 MSVC 编译器,使用 Ctrl+F5 运行以避免调试器有用:

All of this is fairly poorly documented as pointed out in the comments. The proof is in the pudding. Here's an example program that you can play with. It demonstrates how SEH exceptions still allows for C++ destructors to be called, provided you compile with /EHa and how C++ exceptions are implemented on top of SEH. MSVC compiler required, run with Ctrl+F5 to avoid the debugger being helpful:

#include "stdafx.h"
#include <windows.h>
#include <iostream>

// NOTE: the value of the C/C++, Code Generation, Enable C++ Exceptions setting in important
// Try it both with /EHsc (the default) and /EHa to see the difference

class Example {  
public:
    ~Example() { std::cout << "destructed" << std::endl; }
};

int filterException(int code, PEXCEPTION_POINTERS ex) {
    std::cout << "Filtering " << std::hex << code << std::endl;
    return EXCEPTION_EXECUTE_HANDLER;
}

void testProcessorFault() {
    Example e;
    int* p = 0;
    *p = 42;
}

void testCppException() {
    Example e;
    throw 42;
}

int main()
{
    __try {
        testProcessorFault();
    }
    __except(filterException(GetExceptionCode(), GetExceptionInformation())) {
        std::cout << "caught" << std::endl;
    }
    __try {
        testCppException();
    }
    __except(filterException(GetExceptionCode(), GetExceptionInformation())) {
        std::cout << "caught" << std::endl;
    }
    return 0;
}

输出:

Filtering c0000005
destructed
caught
Filtering e06d7363
destructed
caught

这篇关于C++、__try 和 try/catch/finally的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

上一篇:为什么要保守地使用异常? 下一篇:GDB 抱怨缺少 raise.c

相关文章