{"id":667,"date":"2022-05-09T16:56:00","date_gmt":"2022-05-09T09:56:00","guid":{"rendered":"https:\/\/csharptutorial.net\/?page_id=667"},"modified":"2022-06-03T15:08:25","modified_gmt":"2022-06-03T08:08:25","slug":"csharp-try-catch-finally","status":"publish","type":"page","link":"https:\/\/www.csharptutorial.net\/csharp-tutorial\/csharp-try-catch-finally\/","title":{"rendered":"C# try catch finally"},"content":{"rendered":"\n<p><strong>Summary<\/strong>: in this tutorial, you&#8217;ll learn how to use the C# <code>try...catch...finally<\/code> statement to handle exceptions and clean up resources.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Introduction to the C# try&#8230;catch&#8230;finally statement<\/h2>\n\n\n\n<p>The <code><a href=\"https:\/\/csharptutorial.net\/csharp-tutorial\/csharp-try-catch\/\">try...catch<\/a><\/code> statement has an optional <code>finally<\/code> clause as follows:<\/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\">try<\/span>\n{\n    <span class=\"hljs-comment\">\/\/ execute statement<\/span>\n}\n<span class=\"hljs-keyword\">catch<\/span> (<span class=\"hljs-keyword\">Exception<\/span> e)\n{\n    <span class=\"hljs-comment\">\/\/ handle execeptions<\/span>\n}\n<span class=\"hljs-keyword\">finally<\/span>\n{\n    <span class=\"hljs-comment\">\/\/ always execute<\/span>\n}<\/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>When a <code>try...catch<\/code> statement contains a <code>finally<\/code>, it always executes the <code>finally<\/code> block whether an exception occurs inside the <code>try<\/code> block or not:<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li>If no exception occurs inside the <code>try<\/code> block, the control skips over any <code>catch<\/code> block and goes to the <code>finally<\/code> block.<\/li><li>If an exception occurs inside the <code>try<\/code> block, the appropriate <code>catch<\/code> clauses are executed followed by the execution of the <code>finally<\/code> block.<\/li><\/ul>\n\n\n\n<p>It&#8217;s important to note that even if the <code>try<\/code> clause has a <code>return<\/code> statement, the <code>finally<\/code> block will always execute.<\/p>\n\n\n\n<p>Also, the <code>finally<\/code> block cannot contain a <code>return<\/code> statement. Otherwise, the program will fail to compile.<\/p>\n\n\n\n<p>In practice, you often use the <code>finally<\/code> block to clean up the resources such as closing a stream or a database connection.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">C# try&#8230;catch&#8230;finally statement example<\/h2>\n\n\n\n<p>Let&#8217;s take some examples of using the <code>try...catch..finally<\/code> statment.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">1) Using the C# try&#8230;catch&#8230;finally statement example<\/h3>\n\n\n\n<p>The following program reads a text file line by line and displays the file contents to the console. It uses the <code>try...catch...finally<\/code> statement to handle exceptions:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-2\" data-shcb-language-name=\"PHP\" data-shcb-language-slug=\"php\"><span><code class=\"hljs language-php\">StreamReader? reader = <span class=\"hljs-keyword\">null<\/span>;\n<span class=\"hljs-keyword\">try<\/span>\n{\n    reader = <span class=\"hljs-keyword\">new<\/span> StreamReader(@<span class=\"hljs-string\">\"C:\\csharptutorial\\test.txt\"<\/span>);\n    string? line = reader.ReadLine();\n    <span class=\"hljs-keyword\">while<\/span> (line != <span class=\"hljs-keyword\">null<\/span>)\n    {\n        Console.WriteLine(line);\n        line = reader.ReadLine();\n    }\n}\n<span class=\"hljs-keyword\">catch<\/span> (<span class=\"hljs-keyword\">Exception<\/span> e)\n{\n    Console.WriteLine($<span class=\"hljs-string\">\"Error: {e.Message}\"<\/span>);\n}\n<span class=\"hljs-keyword\">finally<\/span>\n{\n    <span class=\"hljs-comment\">\/\/close the file<\/span>\n    <span class=\"hljs-keyword\">if<\/span> (reader != <span class=\"hljs-keyword\">null<\/span>) reader.Close();\n}<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-2\"><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>In this example, the <code>finally<\/code> block closes the stream reader whether an exception occurs inside the <code>try<\/code> block or not.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">2) Using the C# try&#8230;catch&#8230;finally statement with the return statement<\/h3>\n\n\n\n<p>The following illustrates the control flow of the program when using a <code>return<\/code> statement inside the <code>try<\/code> block:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-3\" data-shcb-language-name=\"PHP\" data-shcb-language-slug=\"php\"><span><code class=\"hljs language-php\">\n\nint Test()\n{\n    int result = <span class=\"hljs-number\">100<\/span>;\n    <span class=\"hljs-keyword\">try<\/span>\n    {\n        <span class=\"hljs-keyword\">return<\/span> result;\n    }\n    <span class=\"hljs-keyword\">catch<\/span> (<span class=\"hljs-keyword\">Exception<\/span> e) \n    {\n        Console.WriteLine(e.Message);\n    } \n    <span class=\"hljs-keyword\">finally<\/span>\n    {\n        result = <span class=\"hljs-number\">200<\/span>;\n        Console.WriteLine(<span class=\"hljs-string\">\"Execute the finally block...\"<\/span>);\n    }\n\n    <span class=\"hljs-comment\">\/\/ these statement won't execute<\/span>\n    Console.WriteLine(<span class=\"hljs-string\">\"Bye!\"<\/span>);\n    <span class=\"hljs-keyword\">return<\/span> result;\n}\n\nConsole.WriteLine(Test());<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-3\"><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>Output:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-4\" data-shcb-language-name=\"JavaScript\" data-shcb-language-slug=\"javascript\"><span><code class=\"hljs language-javascript\">Execute the <span class=\"hljs-keyword\">finally<\/span> block...\n<span class=\"hljs-number\">100<\/span><\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-4\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">JavaScript<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">javascript<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>In this example, the program returns the <code>result<\/code> variable in the <code>try<\/code> block. The program also executes the <code>finally<\/code> block. However, it ends immediately as long as it reaches the end of the <code>finally<\/code> block.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Summary<\/h2>\n\n\n\n<ul class=\"wp-block-list\"><li>Use the <code>C# try...catch...finally<\/code> block to handle exceptions and clean up the resources.<\/li><li>The <code>finally<\/code> block always executes whether an exception occurs in the <code>try<\/code> block or not.<\/li><\/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=\"667\"\n\t\t\t\tdata-post-url=\"https:\/\/www.csharptutorial.net\/csharp-tutorial\/csharp-try-catch-finally\/\"\n\t\t\t\tdata-post-title=\"C# try catch finally\"\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=\"667\"\n\t\t\t\tdata-post-url=\"https:\/\/www.csharptutorial.net\/csharp-tutorial\/csharp-try-catch-finally\/\"\n\t\t\t\tdata-post-title=\"C# try catch finally\"\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 use the C# try&#8230;catch&#8230;finally statement to handle exceptions and clean up resources. Introduction to the C# try&#8230;catch&#8230;finally statement The try&#8230;catch statement has an optional finally clause as follows: When a try&#8230;catch statement contains a finally, it always executes the finally block whether an exception occurs inside the [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"parent":7,"menu_order":59,"comment_status":"closed","ping_status":"closed","template":"","meta":{"footnotes":""},"class_list":["post-667","page","type-page","status-publish","hentry"],"_links":{"self":[{"href":"https:\/\/www.csharptutorial.net\/wp-json\/wp\/v2\/pages\/667","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=667"}],"version-history":[{"count":2,"href":"https:\/\/www.csharptutorial.net\/wp-json\/wp\/v2\/pages\/667\/revisions"}],"predecessor-version":[{"id":669,"href":"https:\/\/www.csharptutorial.net\/wp-json\/wp\/v2\/pages\/667\/revisions\/669"}],"up":[{"embeddable":true,"href":"https:\/\/www.csharptutorial.net\/wp-json\/wp\/v2\/pages\/7"}],"wp:attachment":[{"href":"https:\/\/www.csharptutorial.net\/wp-json\/wp\/v2\/media?parent=667"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}