简体   繁体   中英

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

Could any one explain, why am I not getting exception from blow 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 replace Action "myact" with method "myact()" then I can get exception and it can be handeled with try catch block.

public static void myact( ) {
  throw new Exception( "test" );
}
Task myactTask = Task.Factory.StartNew( ( ) => myact);

This does not execute your action, it is a function that returns a reference to your Action.

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

This will execute it and throw/catch the exception.

This happens because you're catching only a AggregateException not a Exception . Another problem is that you're not really 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;
}

I coppied the code and it didn't compile however most of the answers are correct, it is down to 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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM