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" );
}

Answers


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;
}

Need Your Help

HttpPost Method in MVC4 does not return the correct View

asp.net-mvc-4 view return http-post

In one of my views, the Index View of the Scoring controller, I display some images and make them clickable using javascript. When the images have been clicked I populate an array. Once the user cl...

Problem with debugging (method never called)

c# visual-studio-2008 debugging stored-procedures

I am trying to execute a stored procedure, but the following line is giving me trouble:

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.