2010-12-06 30 views
1

我有以下问题。我想要捕获如下所示的异常,而不是我得到NullReferenceException。有没有办法捕捉到这个Anonymous方法中抛出的异常?以匿名方式投掷(捕捉)异常

SynchronizationContext _debug_curr_ui = SynchronizationContext.Current; 

_debug_curr_ui.Send(new SendOrPostCallback(delegate(object state) { 
      throw new Exception("RESONANCE CASCADE: GG-3883 hazardous material failure"); 
}),null); 

我将不胜感激任何帮助。

回答

1

你仍然可以使用try/catch您的匿名方法内部:

_debug_curr_ui.Send(new SendOrPostCallback(delegate(object state) { 
    try 
    { 
     throw new Exception("RESONANCE CASCADE: GG-3883 hazardous material failure"); 
    } 
    catch (Exception ex) 
    { 
     // TODO: do something useful with the exception 
    } 
}), null); 

作为替代方案,你可以修改这个Send方法,只是调用委托之前捕获异常:

public void Send(SendOrPostCallback del) 
{ 
    // ... 

    try 
    { 
     del(); 
    } 
    catch (Exception ex) 
    { 
     // TODO: do something useful with the exception 
    } 

    // ... 
} 
+1

如果你要扔,然后立即捕获并处理你可能也不会抛出呢? – TimC 2010-12-06 14:26:24

0

如果我没有理解正确地说,您希望匿名委托抛出异常,并且您想要在匿名委托外的某个位置捕获此异常。

为了回答这个问题,我们需要知道你实际上在委托中做了什么,以及它是如何被调用的。或者,更具体地说,_debug_curr_ui.Send方法是如何处理委托的?

0

类似下面

 delegate(object obj) 
     { 
      try 
      { 
      } 
      catch(Exception ex) 
      { 
      } 
     } 
1

我怀疑你得到的NullReferenceException因为_debug_curr_ui为空。

否则,您应该能够包装您在try/catch块中发布的代码并捕获这些消息。你也应该考虑使用ApplicationException而不是Exception。

try 
{ 
    Action someMethod = delegate() { throw new ApplicationException("RESONANCE CASCADE: GG-3883 hazardous material failure"); }; 
    someMethod(); 
} 
catch 
{ 
    Console.WriteLine("ex caught"); 
} 

MSDN ApplicationException