{"id":821,"date":"2023-03-09T13:43:34","date_gmt":"2023-03-09T06:43:34","guid":{"rendered":"https:\/\/csharptutorial.net\/?page_id=821"},"modified":"2023-03-21T07:20:54","modified_gmt":"2023-03-21T00:20:54","slug":"csharp-task-handle-exception","status":"publish","type":"page","link":"https:\/\/www.csharptutorial.net\/csharp-concurrency\/csharp-task-handle-exception\/","title":{"rendered":"Handling Exceptions in C# Task"},"content":{"rendered":"\n<p><strong>Summary<\/strong>: in this tutorial, you&#8217;ll learn how to handle exceptions raised by the asynchronous operation executed by the <code>Task<\/code> objects.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Introduction to AggregateException<\/h2>\n\n\n\n<p>In general, when a <code><a href=\"https:\/\/csharptutorial.net\/csharp-concurrency\/csharp-task\/\">Task<\/a><\/code> encounters an exception, it will propagate the exception to the calling thread. If a <code>Task<\/code> contains nested tasks, any asynchronous operations performed within these tasks may also result in multiple exceptions being thrown.<\/p>\n\n\n\n<p>To propagate all the exceptions to the calling thread, the <code>Task<\/code> wraps them in an <code><code>AggregateException<\/code><\/code> object. <\/p>\n\n\n\n<p>The <code><code>AggregateException<\/code><\/code> object has the <code>InnerExceptions<\/code> property that contains all the original exceptions. The <code>InnerExceptions<\/code> is a read-only collection of the <code>Exception<\/code> instances.<\/p>\n\n\n\n<p>To handle these exceptions, you can enumerate them through the <code>InnerExceptions<\/code> property of the <code>AggregateException<\/code> object using a <code>foreach<\/code> loop.<\/p>\n\n\n\n<p>Alternatively, you can handle the original exceptions using the <code>AggregateException.Handle<\/code> method:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-1\" data-shcb-language-name=\"PHP\" data-shcb-language-slug=\"php\"><span><code class=\"hljs language-php\"><span class=\"hljs-keyword\">public<\/span> void Handle (Func&lt;<span class=\"hljs-keyword\">Exception<\/span>,bool&gt; predicate);<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-1\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">PHP<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">php<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>It&#8217;s important to note that the <code>Task<\/code> will wrap any exceptions that occur within an <code>AggregationException<\/code> object, even if a single exception is raised.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Handling AggregateException example<\/h2>\n\n\n\n<p>The following program illustrates how to handle exceptions in an asynchronous operation executed by a task.<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-2\" data-shcb-language-name=\"C#\" data-shcb-language-slug=\"cs\"><span><code class=\"hljs language-cs\"><span class=\"hljs-function\"><span class=\"hljs-keyword\">decimal<\/span> <span class=\"hljs-title\">Divide<\/span>(<span class=\"hljs-params\"><span class=\"hljs-keyword\">decimal<\/span> a, <span class=\"hljs-keyword\">decimal<\/span> b<\/span>)<\/span>\n{\n    Thread.Sleep(<span class=\"hljs-number\">1000<\/span>);\n\n    <span class=\"hljs-keyword\">return<\/span> a \/ b;\n}\n\n<span class=\"hljs-keyword\">try<\/span>\n{\n    <span class=\"hljs-keyword\">var<\/span> task = Task.Run(() =&gt; Divide(<span class=\"hljs-number\">10<\/span>, <span class=\"hljs-number\">0<\/span>));\n    <span class=\"hljs-keyword\">var<\/span> result = task.Result;\n}\n<span class=\"hljs-keyword\">catch<\/span> (AggregateException ae)\n{\n    ae.Flatten().Handle(e =&gt;\n    {\n        <span class=\"hljs-keyword\">if<\/span> (e <span class=\"hljs-keyword\">is<\/span> DivideByZeroException)\n        {\n            Console.WriteLine(e.Message);\n            <span class=\"hljs-keyword\">return<\/span> <span class=\"hljs-literal\">true<\/span>;\n        }\n        <span class=\"hljs-keyword\">else<\/span>\n        {\n            <span class=\"hljs-keyword\">throw<\/span> e;\n        }\n    });\n}<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-2\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">C#<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">cs<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>How it works.<\/p>\n\n\n\n<p>First, define a method <code>Divide()<\/code> that takes two decimal numbers and returns the result of dividing them after a delay of one second:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-3\" data-shcb-language-name=\"C#\" data-shcb-language-slug=\"cs\"><span><code class=\"hljs language-cs\"><span class=\"hljs-function\"><span class=\"hljs-keyword\">decimal<\/span> <span class=\"hljs-title\">Divide<\/span>(<span class=\"hljs-params\"><span class=\"hljs-keyword\">decimal<\/span> a, <span class=\"hljs-keyword\">decimal<\/span> b<\/span>)<\/span>\n{\n    Thread.Sleep(<span class=\"hljs-number\">1000<\/span>);\n\n    <span class=\"hljs-keyword\">return<\/span> a \/ b;\n}<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-3\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">C#<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">cs<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>Second, use the <code><code>Task.Run<\/code>()<\/code> method to run the <code>Divide()<\/code> method asynchronously in a separate thread. Since we use the arguments 10 and 0, the <code>Divide()<\/code> method will throw a <code>DivideByZeroException<\/code> exception:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-4\" data-shcb-language-name=\"C#\" data-shcb-language-slug=\"cs\"><span><code class=\"hljs language-cs\"><span class=\"hljs-keyword\">var<\/span> task = Task.Run(() =&gt; Divide(<span class=\"hljs-number\">10<\/span>, <span class=\"hljs-number\">0<\/span>));<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-4\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">C#<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">cs<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>Third, use the <a href=\"https:\/\/csharptutorial.net\/csharp-tutorial\/csharp-try-catch\/\">try&#8230;catch<\/a> block to catch any exceptions thrown by the method. Since the asynchronous operation throws an <code>AggregateException<\/code>, we catch and handle it in the <code>catch<\/code> block.<\/p>\n\n\n\n<p>In the exception handler, we use the <code>Handle()<\/code> method of the <code>AggregateException<\/code> class to handle each inner exception.<\/p>\n\n\n\n<p>If the exception is <code>DivideByZeroException<\/code>, the program outputs the error message to the console. Otherwise, it rethrows the same exception.<\/p>\n\n\n\n<p>When you run the program, you&#8217;ll see the following output:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-5\" data-shcb-language-name=\"C#\" data-shcb-language-slug=\"cs\"><span><code class=\"hljs language-cs\">Attempted to divide <span class=\"hljs-keyword\">by<\/span> zero.<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-5\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">C#<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">cs<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<h2 class=\"wp-block-heading\">Summary<\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Use the <code>try...catch<\/code> to catch the <code>AggregateException<\/code> thrown by the asynchronous operation executed by a <code>Task<\/code>.<\/li>\n\n\n\n<li>Use the <code>AggregateException.Handle()<\/code> method to handle exceptions.<\/li>\n<\/ul>\n<div class=\"helpful-block-content\" data-title=\"\">\n\t<header>\n\t\t<div class=\"wth-question\">Was this tutorial helpful ?<\/div>\n\t\t<div class=\"wth-thumbs\">\n\t\t\t<button\n\t\t\t\tdata-post=\"821\"\n\t\t\t\tdata-post-url=\"https:\/\/www.csharptutorial.net\/csharp-concurrency\/csharp-task-handle-exception\/\"\n\t\t\t\tdata-post-title=\"Handling Exceptions in C# Task\"\n\t\t\t\tdata-response=\"1\"\n\t\t\t\tclass=\"wth-btn-rounded wth-yes-btn\"\n\t\t\t>\n\t\t\t\t<svg\n\t\t\t\t\txmlns=\"http:\/\/www.w3.org\/2000\/svg\"\n\t\t\t\t\tviewBox=\"0 0 24 24\"\n\t\t\t\t\tfill=\"none\"\n\t\t\t\t\tstroke=\"currentColor\"\n\t\t\t\t\tstroke-width=\"2\"\n\t\t\t\t\tstroke-linecap=\"round\"\n\t\t\t\t\tstroke-linejoin=\"round\"\n\t\t\t\t\tclass=\"feather feather-thumbs-up block w-full h-full\"\n\t\t\t\t>\n\t\t\t\t\t<path\n\t\t\t\t\t\td=\"M14 9V5a3 3 0 0 0-3-3l-4 9v11h11.28a2 2 0 0 0 2-1.7l1.38-9a2 2 0 0 0-2-2.3zM7 22H4a2 2 0 0 1-2-2v-7a2 2 0 0 1 2-2h3\"\n\t\t\t\t\t><\/path>\n\t\t\t\t<\/svg>\n\t\t\t\t<span class=\"sr-only\"> Yes <\/span>\n\t\t\t<\/button>\n\n\t\t\t<button\n\t\t\t\tdata-response=\"0\"\n\t\t\t\tdata-post=\"821\"\n\t\t\t\tdata-post-url=\"https:\/\/www.csharptutorial.net\/csharp-concurrency\/csharp-task-handle-exception\/\"\n\t\t\t\tdata-post-title=\"Handling Exceptions in C# Task\"\n\t\t\t\tclass=\"wth-btn-rounded wth-no-btn\"\n\t\t\t>\n\t\t\t\t<svg\n\t\t\t\t\txmlns=\"http:\/\/www.w3.org\/2000\/svg\"\n\t\t\t\t\tviewBox=\"0 0 24 24\"\n\t\t\t\t\tfill=\"none\"\n\t\t\t\t\tstroke=\"currentColor\"\n\t\t\t\t\tstroke-width=\"2\"\n\t\t\t\t\tstroke-linecap=\"round\"\n\t\t\t\t\tstroke-linejoin=\"round\"\n\t\t\t\t>\n\t\t\t\t\t<path\n\t\t\t\t\t\td=\"M10 15v4a3 3 0 0 0 3 3l4-9V2H5.72a2 2 0 0 0-2 1.7l-1.38 9a2 2 0 0 0 2 2.3zm7-13h2.67A2.31 2.31 0 0 1 22 4v7a2.31 2.31 0 0 1-2.33 2H17\"\n\t\t\t\t\t><\/path>\n\t\t\t\t<\/svg>\n\t\t\t\t<span class=\"sr-only\"> No <\/span>\n\t\t\t<\/button>\n\t\t<\/div>\n\t<\/header>\n\n\t<div class=\"wth-form hidden\">\n\t\t<div class=\"wth-form-wrapper\">\n\t\t\t<div class=\"wth-title\"><\/div>\n\t\t\t\n\t\t\t<textarea class=\"wth-message\"><\/textarea>\n\n\t\t\t<button class=\"btn btn-primary wth-btn-submit\">Send<\/button>\n\t\t\t<button class=\"btn wth-btn-cancel\">Cancel<\/button>\n\t\t\n\t\t<\/div>\n\t<\/div>\n<\/div>\n","protected":false},"excerpt":{"rendered":"<p>Summary: in this tutorial, you&#8217;ll learn how to handle exceptions raised by the asynchronous operation executed by the Task objects. Introduction to AggregateException In general, when a Task encounters an exception, it will propagate the exception to the calling thread. If a Task contains nested tasks, any asynchronous operations performed within these tasks may also [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"parent":760,"menu_order":5,"comment_status":"closed","ping_status":"closed","template":"","meta":{"footnotes":""},"class_list":["post-821","page","type-page","status-publish","hentry"],"_links":{"self":[{"href":"https:\/\/www.csharptutorial.net\/wp-json\/wp\/v2\/pages\/821","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.csharptutorial.net\/wp-json\/wp\/v2\/pages"}],"about":[{"href":"https:\/\/www.csharptutorial.net\/wp-json\/wp\/v2\/types\/page"}],"author":[{"embeddable":true,"href":"https:\/\/www.csharptutorial.net\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.csharptutorial.net\/wp-json\/wp\/v2\/comments?post=821"}],"version-history":[{"count":4,"href":"https:\/\/www.csharptutorial.net\/wp-json\/wp\/v2\/pages\/821\/revisions"}],"predecessor-version":[{"id":1149,"href":"https:\/\/www.csharptutorial.net\/wp-json\/wp\/v2\/pages\/821\/revisions\/1149"}],"up":[{"embeddable":true,"href":"https:\/\/www.csharptutorial.net\/wp-json\/wp\/v2\/pages\/760"}],"wp:attachment":[{"href":"https:\/\/www.csharptutorial.net\/wp-json\/wp\/v2\/media?parent=821"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}