捕获没有try / catch的异常 [英] Catching exceptions thrown without try/catch

查看:236
本文介绍了捕获没有try / catch的异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我记得阅读关于如何在不使用try / catch的情况下捕获异常。基本上当通过反索引一个空指针抛出一个异常,例如未处理的异常时,即使try / catch没有为该异常编码,也会有一个进程被触发。我相信它与一个顶级库,你写,然后包括在你的代码。不幸的是,关于这种方法的文档似乎不存在,但我已经看到/听说过这样的方法之前。

I recall reading about how exceptions could be caught without the use of try/catch. Basically when an exception is thrown such as "Unhandled exception" via derefencing a null pointer, there would be a process that is triggered even when a try/catch is not coded for the exception. I believe it had something to do with a top level library that you write then include in your code. Unfortunately documentation on such a method seems to be non-existent but I have seen/heard of such a method being done before. Could someone please explain how this is done?

推荐答案

在C ++中,取消引用空指针会导致未定义的行为,这不一定意味着抛出异常。例如,在Unix系统上,会出现SIGSEGV信号。

In C++, dereferencing a null pointer causes undefined behavior, which does not necessarily imply that an exception is thrown. On Unix systems, for example, a SIGSEGV signal is raised instead.

在Windows上,访问冲突会导致 SEH 例外。 SEH异常与C ++异常不一样;则使用 __ try / __ except 语句(而不是 try / catch 语句)。未处理的SEH异常调用未处理的异常过滤器,您可以使用 SetUnhandledExceptionFilter

On Windows, access violations raise a SEH exception. SEH exceptions are not the same as C++ exception; they are handled using __try/__except statements (as opposed to try/catch statements). An unhandled SEH exception invokes unhandled exception filter, which you can set using SetUnhandledExceptionFilter.

#include <Windows.h>
#include <iostream>

LONG WINAPI MyFilter(EXCEPTION_POINTERS * /*ExceptionInfo*/)
{
    std::cout << "An uncaught exception was detected!\n";

    // Ultimately causes Windows Error Reporting to be invoked.
    // Use EXCEPTION_EXECUTE_HANDLER to silently terminate the application.
    return EXCEPTION_CONTINUE_SEARCH;
}

int main()
{
    SetUnhandledExceptionFilter(MyFilter);
    *(char volatile *)0 = 0;
}

这篇关于捕获没有try / catch的异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆