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:

enter image description here

what ide looks when breaks:

enter image description here

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

Popular posts from this blog

Magento/PHP - Get phones on all members in a customer group -

php - Bypass Geo Redirect for specific directories -

php - .htaccess mod_rewrite for dynamic url which has domain names -