简体   繁体   English

在C#中,抛出异常时能否执行代码?

[英]in C# can I have code execute when an exception is thrown?

I've got a bug that is really difficult for me to track. 我遇到了一个非常难以跟踪的错误。 It's one of those that only occurs when the debugger isnt connected :) 这是仅在调试器未连接时才会发生的一种:)

I've pinvoked MiniDumpWriteDump() and that works really well for creating .dmp files that I can debug after the fact. 我已经选好了MiniDumpWriteDump(),这对于创建.dmp文件非常有效,事后我可以对其进行调试。

however, I'm doing something like 但是,我正在做类似的事情

try
{
    foo();
}
catch(Exception)
{
    CreateMiniDump()
}

this works great, however I dont get the callstack that is desired. 这很好,但是我没有得到所需的调用栈。 I'd really prefer to have the callstack (with all the member variables) at the point where the exception was thrown. 我真的更喜欢在引发异常的地方使用调用堆栈(包含所有成员变量)。

is this possible? 这可能吗? Is there a mechanism to get first dibs on the exception? 有没有一种机制可以使异常发生? such that I can create a minidump and preserve the callstack, etc? 这样我就可以创建一个小型转储并保留调用栈,等等?

You can subscribe to AppDomain.CurrentDomain.UnhandledException to get an event that is raised when an exception is about to unwind. 您可以订阅AppDomain.CurrentDomain.UnhandledException以获取在异常即将解散时引发的事件。 When it's raised, the original context is still on the stack. 引发时,原始上下文仍在堆栈中。 You could put your minidump creation code inside of your event handler. 您可以将小型转储创建代码放入事件处理程序中。

在.NET 4及更高版本中,您可以订阅FirstChanceException事件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 当我尝试关闭响应时,抛出C#FTPWebReponse异常 - C# FTPWebReponse exception is thrown when I try to close a reponse 为什么我有这个错误? 抛出异常:System.dll C# 中的“System.Net.WebException” - Why do i have this error? Exception thrown: 'System.Net.WebException' in System.dll C# 您可以捕获使用Powershell调用C#控制台应用程序引发的错误代码和异常信息吗? - Can you catch the error code and exception information thrown using Powershell to call C# console Application? C#中抛出异常后如何继续代码执行? - How to continue code execution after the exception is thrown in C#? sqlServer问题:当我想在C#中的表中输入数据时,数据未在其中注册。 没有异常抛出 - sqlServer prob: When i want to enter data in a table in c#, the data are not registered in it. No exception thrown 当C#中变量的值发生变化时,如何执行代码? - How can I execute code when value of a variable changes in C#? c#Exception抛出(不在)构造函数中 - c# Exception Thrown at (not in) Constructor C#“如果抛出异常...” - C# "if exception is thrown..." ANTLR C#不引发异常 - ANTLR C# No Exception Thrown 当我从 C# 代码调用导入的 C++ 函数时,为什么会抛出 AccessViolationException? - Why is an AccessViolationException thrown when I call an imported C++ function from C# code?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM