How to catch exceptions from Action containing an anonymous method in C #?

Can anyone explain why I am not getting an exception from the hit code:

Action <Exception> myact = ( ) => { throw new Exception( "test" ); }; Task myactTask = Task.Factory.StartNew( ( ) => myact); try { myactTask.Wait( ); Console.WriteLine( myactTask.Id.ToString( ) ); Console.WriteLine( myactTask.IsCompleted.ToString( ) ); } catch( AggregateException ex ) { throw ex; } 

on the other hand, if you replace the action "myact" with the method "myact ()", then I can get an exception and it can be handled using the catch catch block.

 public static void myact( ) { throw new Exception( "test" ); } 
+4
source share
3 answers
 Task myactTask = Task.Factory.StartNew( ( ) => myact); 

This does not perform your action, it is a function that returns a link to your action.

 Task myactTask = Task.Factory.StartNew(myact); 

This will execute it and throw / catch the exception.

+4
source

This is because you are catching only an AggregateException not a Exception . Another problem is that you are not executing your code on Task.Factory.StartNew .

Change your code to something like:

 Action <Exception> myact = ( ) => { throw new Exception("test"); }; Task myactTask = Task.Factory.StartNew(myact); try { myactTask.Wait(); Console.WriteLine(myactTask.Id.ToString()); Console.WriteLine(myactTask.IsCompleted.ToString()); } catch(Exception ex) { throw ex; } 
0
source

I copied the code and it did not compile, however most of the answers are correct, this is not what you are trying to catch.

 //Action<in Exception> : Make the delgate take an exception, then throw it Action<Exception> myact = (ex => { throw ex; }); //Pass a new Exception with the message test "Test" that will be thrown Task myactTask = Task.Factory.StartNew(() => myact(new Exception("Test"))); try { myactTask.Wait(); Console.WriteLine(myactTask.Id.ToString()); Console.WriteLine(myactTask.IsCompleted.ToString()); } catch (Exception ex) { //Writes out "Test" Console.WriteLine(ex.Message); throw ex; } 
0
source

All Articles