Throwing (and catching) exception in anonymous method
I have following problem. I want to catch exception as shown below, instead I get NullReference开发者_C百科Exception. Is there a way to catch the exception thrown inside of this Anonymous method ?
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);
I would appreciate any help.
You could still use try/catch
inside your anonymous method:
_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);
As an alternative you could modify this Send
method and catch the exception just before invoking the delegate:
public void Send(SendOrPostCallback del)
{
// ...
try
{
del();
}
catch (Exception ex)
{
// TODO: do something useful with the exception
}
// ...
}
I suspect that you are getting the NullReferenceException because _debug_curr_ui is null.
Otherwise you should be able to wrap the code that you posted in a try/catch block and catch the excpetion. You should also think about using ApplicationException and not Exception.
try
{
Action someMethod = delegate() { throw new ApplicationException("RESONANCE CASCADE: GG-3883 hazardous material failure"); };
someMethod();
}
catch
{
Console.WriteLine("ex caught");
}
MSDN ApplicationException
If I understand correctly, you want the anonymous delegate to throw the exception, and you want to catch this exception somewhere outside of the anonymous delegate.
In order to answer that, we will need to know what you are actually doing with the delegate, and how it is being invoked. Or, to be more specific, what does the _debug_curr_ui.Send
method do with the delegate?
something like below
delegate(object obj)
{
try
{
}
catch(Exception ex)
{
}
}
精彩评论