In this article we will explore how to handle exceptions thrown from one or more tasks.We will explore the uses Flatten method in System.AggregateException. Flatten method throws all the innerexception of AggregateException as single AggregateException.
Let's write some code.
Put below lines of executable code on a button click event.
private void button1_Click(object sender, EventArgs e) { int[] zero = { 0 }; Task<int>[] tasks = new Task<int>[2]; //Divide by zero exception tasks[0] = TaskEx.Run(() => 10 / zero[0]); //Index out of range exception tasks[1] = TaskEx.Run(() => zero[2]); try { Task.WaitAll(tasks); } catch (AggregateException ae) { throw ae.Flatten(); } }
When above code will execute it will throw divide by zero exception and index out of range exception. Both the exception will be caught by Flatten and inner exceptio will look like below image.

We can also handle each inner exception like below
private void button1_Click(object sender, EventArgs e) { int[] zero = { 0 }; Task<int>[] tasks = new Task<int>[2]; //Divide by zero exception tasks[0] = TaskEx.Run(() => 10 / zero[0]); //Index out of range exception tasks[1] = TaskEx.Run(() => zero[2]); try { Task.WaitAll(tasks); } catch (AggregateException ae) { ae.Handle(ex => { if (ex is DivideByZeroException) { //Log the exception return true; } if (ex is IndexOutOfRangeException) { //Log the exception return true; } return false; // Unhandled exception will stop the application }); } }
This ends the article of handling exceptions thrown by tasks.
|