In this recipe, we will look at another way to handle System.AggregateException
, by using the AggregateException.Handle
method. The Handler
method invokes a handler function for each exception wrapped in AggregateException
.
For this recipe, we need to turn off the Visual Studio 2012 Exception Assistant. The Exception Assistant appears whenever a runtime exception is thrown and intercepts the exception before it gets to our handler.
To turn off the Exception Assistant, go to the Debug menu and select Exceptions.
Uncheck the user-unhandled checkbox next to Common Language Runtime Exceptions.
Let's take a look at how we can use AggregateException.Handle
to provide an alternate method to handling exceptions in a parallel application.
For this recipe, we will return to our WordCount6 project, and modify it to handle our exceptions in a different way. Start Visual Studio 2012 and open the WordCount6 project.
The first step is to define our handler function that will be invoked when we call
AggregateException.Handle
. Following theMain
method of yourProgram
class, add a newprivate static handler
method that returns a bool. It should look as the following code snippet:private static bool HandleWebExceptions(Exception ex) { if (ex is WebException) { Console.WriteLine(("Caught WebException: {0}", ex.Message); return true; } else { Console.WriteLine("Caught exception: {0}", ex.Message); return false; } }
The only other step here is to replace the body of your
catch
block with a call toSystem.AggregateException.Handle
, passing in theHandleWebExceptions
predicate. The updatedtry
/catch
block should look as follows:try { task1.Wait(); if (!task1.IsFaulted) { Console.WriteLine("Task complete. Origin of Species word count: {0}",task1.Result); } } catch (AggregateException aggEx) { aggEx.Handle(HandleWebExceptions); }
Those are the only modifications necessary. In Visual Studio 2012, press F5 to run the project. You should see output as shown in the following screenshot:
AggregateException.Handle()
takes a predicate that you supply, and the predicate will be invoked once for every exception wrapped in System.AggregateException
.
The predicate itself just needs to contain the logic to handle the various exception types that you expect, and to return true or false to indicate whether the exception was handled.
If any of the exceptions went unhandled, they will be wrapped in a new System.AggregateException
and thrown.