每当在Visual C ++程序中抛出异常时,如何运行一些代码? [英] How can some code be run each time an exception is thrown in a Visual C++ program?

查看:159
本文介绍了每当在Visual C ++程序中抛出异常时,如何运行一些代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果在C ++程序中抛出异常,则控制被传递到异常处理程序或调用 terminate()

If an exception is thrown in a C++ program control is either transferred to the exception handler or terminate() is called.

即使程序从处理程序(或从 terminate() handler)中发出一些诊断,这可能太晚了,最大的价值在于调用

Even if the program emits some diagnostics from inside the handler (or from terminate() handler) that can be too late - the most value is in the call stack at the point where the exception is thrown, not in the handler.

在Windows上,可以使用<$ c $获取调用堆栈,而不是在处理程序中

On Windows a call stack can be obtained using [StackWalk64()]1 function. The key is how to call that function at the right moment.

有一种方法使Visual C ++程序在每次异常(或异常

Is there a way to make a Visual C++ program execute some user code each time an exception (or an exception for which no handler is set) is thrown?

推荐答案

如果你想在SEH异常抛出时做任何事情,比如当发生访问冲突时,您可以简单地捕获SEH异常(使用__finally或者转换为C ++异常(请参阅这里))并访问异常中的上下文,该异常是抛出异常时的上下文。然后,您可以使用StackWalker或迷你转储生成一个调用堆栈。

If you want to do stuff when an SEH exception is thrown, such as when an access violation occurs, then you can simply catch the SEH exception (either with a __finally, or with a conversion to a C++ exception (see here)) and access the context within the exception which is the context at the time the exception was thrown. You can then generate either a callstack using StackWalker or a mini dump. IMHO it's better to produce a mini dump.

如果你想捕获C ++异常,它们被抛出,你不能访问源的C ++异常类,那么你需要得到一点工艺。我通过在自定义调试器下运行目标进程来处理此问题 - 使用Debug API(请参见这里),它获得抛出异常的通知。此时,您可以创建目标进程的微型转储或调用堆栈。

If you want to catch C++ exceptions at the point they're thrown and you don't have access to the source to the C++ exception classes then you need to get a bit craftier. I deal with this problem by running the target process under a custom debugger - use the Debug API (see here) which gets notifications of when an exception is thrown. At that point you can create a mini dump or call stack of the target process.

这篇关于每当在Visual C ++程序中抛出异常时,如何运行一些代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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