C++,__try 和 try/catch/finally

C++, __try and try/catch/finally(C++,__try 和 try/catch/finally)
本文介绍了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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Rising edge interrupt triggering multiple times on STM32 Nucleo(在STM32 Nucleo上多次触发上升沿中断)
How to use va_list correctly in a sequence of wrapper functions calls?(如何在一系列包装函数调用中正确使用 va_list?)
OpenGL Perspective Projection Clipping Polygon with Vertex Outside Frustum = Wrong texture mapping?(OpenGL透视投影裁剪多边形,顶点在视锥外=错误的纹理映射?)
How does one properly deserialize a byte array back into an object in C++?(如何正确地将字节数组反序列化回 C++ 中的对象?)
What free tiniest flash file system could you advice for embedded system?(您可以为嵌入式系统推荐什么免费的最小闪存文件系统?)
Volatile member variables vs. volatile object?(易失性成员变量与易失性对象?)