Handling Exceptions

There is a minor wrinkle when debugging code where you have handled exceptions thrown by Tasks in your code. For an example, see Listing 7-5.

Listing 7-5. A Program That Handles Task Exceptions using System;

using System.Threading.Tasks;

namespace Listing_05 {

class Listing_05 {

static void Main(string[] args) {

Task[] tasks = new Task[2]; for (int i = 0; i < tasks.Length; i++) { tasks[i] = Task.Factory.StartNew(() => { for (int j = 0; j < 5000000; j++) { if (j == 500) {

throw new Exception("Value is 500");

// wait for the tasks and catch any exceptions try {

Task.WaitAll(tasks); } catch (AggregateException ex) { ex.Handle(innerEx => {

Console.WriteLine("Exception message is {0}", innerEx.Message); return true;

When you run this code normally, each Task throws an exception, and these exceptions are wrapped in an instance of System.AggregateException, which is handled by the try. . .catch code block around the Task.WaitAll() method.

However, when you run this code in the debugger, the debugger will break and flag the exceptions as unhandled. To fix this, select "Options and Settings" from the Debug menu in Visual Studio, and uncheck the Enable Just My Code option, as shown in Figure 7-9. This allows for Task exception handling to be handled properly in the debugger.

Figure 7-9. Unchecking the Enable Just My Code debugger option
0 0

Post a comment