C++、__try 和 try/catch/finally
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7049502/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C++, __try and try/catch/finally
提问by martin
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?
我有点想知道 C++ try/catch/finally 块。我见过这些带有两个下划线的命令,比如 __try。但是 MVSC 2010 项目也没有下划线运行。那么什么时候需要这些下划线呢?
回答by Hans Passant
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.
在 Windows 上,在操作系统级别支持异常。称为结构化异常处理 (SEH),它们大致相当于 Unix 信号。为 Windows 生成代码的编译器通常利用这一点,它们使用 SEH 基础结构来实现 C++ 异常。
In keeping with the C++ standard, the throwand catchkeywords only ever throw and catch C++ exceptions. The corresponding SEH exception code for the MSVC compiler is 0xe06d7343. The last 3 bytes are the ASCII code for "msc".
与 C++ 标准保持一致,throw和catch关键字只抛出和捕获 C++ 异常。MSVC 编译器对应的 SEH 异常代码是 0xe06d7343。最后 3 个字节是“msc”的 ASCII 码。
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 throwthe 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.
将它与操作系统支持统一还意味着 C++ 析构函数将在堆栈展开期间为 SEH 异常调用。执行展开的代码在 Windows 内部,并以与任何 SEH 完全相同的方式处理由throw 引发的 SEH。但是,Microsoft 编译器有一个优化,它试图避免生成确保在所有情况下都调用析构函数所需的代码。如果它可以证明在控制对象生命周期的作用域块中没有 throw 语句,那么它会跳过注册代码。这与异步 SEH 异常不兼容,如果您打算捕获 SEH 异常,您应该使用 /EHa 编译选项来取消此优化。
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.
有很多 SEH 异常类型。操作系统可以生成的在ntstatus.h SDK头文件中列出。此外,您可能会与使用 SEH 实现自己的异常处理的代码互操作,他们将使用自己的异常代码。与 .NET 一样,托管异常使用 0xe0434f4d(“com”)异常代码。
To catch SEH exceptions in a C++ program, you must use the non-standard __try keyword. The __except keyword is analogous to the C++ catchkeyword. 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.
要在 C++ 程序中捕获 SEH 异常,您必须使用非标准的 __try 关键字。__except 关键字类似于 C++ catch关键字。它具有更多功能,您可以指定一个异常过滤器表达式来确定是否应捕获活动异常。一切皆有可能,但您通常只查看传递的异常信息,看看您是否有兴趣处理它。__finally 关键字允许您编写在处理异常后运行的代码。在 C++ 中没有等价物,但在其他语言中并不少见。
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:
正如评论中指出的那样,所有这些都没有很好的记录。证据就在布丁里。这是您可以玩的示例程序。它演示了 SEH 异常如何仍然允许调用 C++ 析构函数,前提是您使用 /EHa 进行编译以及如何在 SEH 之上实现 C++ 异常。需要 MSVC 编译器,使用 Ctrl+F5 运行以避免调试器有用:
#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;
}
Output:
输出:
Filtering c0000005
destructed
caught
Filtering e06d7363
destructed
caught
回答by Alok Save
__try
/ __except
is for catching SEH (windows generated errors)not for catching general exceptions.
__try
/__except
用于捕获SEH(Windows 生成的错误)而不是用于捕获一般异常。
try
/ catch
is what the C++ standard specifies for handling general C++ exceptions.
try
/catch
是 C++ 标准为处理一般 C++ 异常指定的内容。
For the standard C++ code you write you should always use try
/ catch
and not __try
/ __except
对于您编写的标准 C++ 代码,您应该始终使用try
/catch
而不是__try
/__except
Also, finally
is not C++ Standard specified construct, It works for you because it is a Microsoft compiler extension.
此外,finally
不是 C++ 标准指定的构造,它对您有用,因为它是Microsoft 编译器扩展。
回答by Ioan Paul Pirau
__try/__except
is Microsoft specificIf you want your code to be compilable with other compilers (for examplec g++) (or) in another OS avoid using them, and stick with the standard try/catch
statements
__try/__except
特定于 Microsoft如果您希望您的代码可以与其他编译器(例如 c g++)(或)在另一个操作系统中编译,请避免使用它们,并坚持使用标准try/catch
语句