c# - Handling asynchronous anonymous method errors -
i have base framework designed deal errors generically; however, when error occurs, appear not catching in framework. following code simplified version of i'm trying achieve:
class program { static void main(string[] args) { runmethod<decimal>(() => { decimal x = 0; decimal y = 1 / x; return y; }); } private static async task<t> runmethod<t>(func<t> method) { try { var result = await tryrunningmehod<t>(method); return result; } catch (dividebyzeroexception ex) { system.diagnostics.debug.writeline("error"); return default(t); } } private static async task<t> tryrunningmehod<t>(func<t> method) { var returnvalue = await task.run<t>(method); return returnvalue; } }
what happens when run above code crashes on divide zero. i'm trying make write debug message , continue.
i have break on unhandled exceptions flagged.
my exceptions settings:
what ide looks when breaks:
you never await runmethod
finish executing application has no chance catch , process exception. has finished , in cleanup phase.
simply change code :
runmethod<decimal>(() => { decimal x = 0; decimal y = 1 / x; return y; }).wait();
and exception handler work expected.
in fact, compiler issues warning this. tools resharper complain , mark call.
by making change, execution enter exception handler. is, nothing appear in console word error
appear in visual studio's output window.
to show error message in console, exception handler should change to:
catch (dividebyzeroexception ex) { console.writeline("error"); return default(t); }
Comments
Post a Comment