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

查看:113
本文介绍了每次在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()处理程序)发出一些诊断程序,这可能太晚了 - 调用中最大的值

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 $()获取调用堆栈,而不是在处理程序中。 c> [StackWalk64()] 1 功能。关键是如何在正确的时刻调用该函数。

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 ++异常)(请参阅 here )),并访问异常中的上下文,该异常是引发异常时的上下文。然后,您可以使用StackWalker或迷你转储生成一个callstack。如果您想要捕获C ++异常,并且您无法访问源代码,那么可以生成一个迷你转储。

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 ++异常类,那么你需要更精细。我通过在自定义调试器下运行目标进程来处理此问题 - 使用Debug API(请参阅 here ),它会在抛出异常时收到通知。此时您可以创建目标进程的小型转储或调用堆栈。

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天全站免登陆