{"id":661,"date":"2022-05-09T15:22:55","date_gmt":"2022-05-09T08:22:55","guid":{"rendered":"https:\/\/csharptutorial.net\/?page_id=661"},"modified":"2023-04-03T11:12:36","modified_gmt":"2023-04-03T04:12:36","slug":"csharp-try-catch","status":"publish","type":"page","link":"https:\/\/www.csharptutorial.net\/csharp-tutorial\/csharp-try-catch\/","title":{"rendered":"C# try catch"},"content":{"rendered":"\n<p><strong>Summary<\/strong>: in this tutorial, you&#8217;ll learn about exceptions and how to use the C# <code>try...catch<\/code> statement to handle exceptions.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Introduction to the C# try catch statement<\/h2>\n\n\n\n<p>Exceptions are runtime errors in a program, which violate system constraints. For example, when the program attempts to divide a number by zero, an exception occurs. When an exception occurs, the system catches it and raises the exception.<\/p>\n\n\n\n<p>If the program doesn&#8217;t handle the exception properly, it will crash. For example, the following program will crash due to an exception:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-1\" data-shcb-language-name=\"C#\" data-shcb-language-slug=\"cs\"><span><code class=\"hljs language-cs\"><span class=\"hljs-keyword\">int<\/span> amount = <span class=\"hljs-number\">100<\/span>;\n<span class=\"hljs-keyword\">int<\/span> qty = <span class=\"hljs-number\">0<\/span>;\n\n<span class=\"hljs-keyword\">int<\/span> result = amount \/ qty;\n\nConsole.WriteLine(result);<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-1\"><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>In this example, the program crashed with the following error message:<\/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\">System.DivideByZeroException: <span class=\"hljs-string\">'Attempted to divide by zero.'<\/span><\/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>In this error message, the exception name is <code>System.DivideByZeroException<\/code>. And the error message indicates that the program attempted to divide by zero.<\/p>\n\n\n\n<p>If you don&#8217;t handle exceptions, users will see unfriendly error messages. To goal of exception handling is to respond to an exception with one of the following actions:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Display a user-friendly message to users and request users to take corrective actions to keep the program running properly.<\/li>\n\n\n\n<li>Log the information of the exception to a file so that you can address it later.<\/li>\n\n\n\n<li>Clean up any external resources such as database connections.<\/li>\n<\/ul>\n\n\n\n<p>To handle exceptions, you use the <code>try...catch<\/code> statement:<\/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-keyword\">try<\/span>\n{\n    <span class=\"hljs-comment\">\/\/ statements to be guarded for exceptions<\/span>\n}\n<span class=\"hljs-keyword\">catch<\/span>\n{\n    <span class=\"hljs-comment\">\/\/ exception handler<\/span>\n\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>In this syntax:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>First, place the statements that you want to guard for exceptions in the <code>try<\/code> block.<\/li>\n\n\n\n<li>Second, provide the exception handler in the <code>catch<\/code> block to handle the exception.<\/li>\n<\/ul>\n\n\n\n<p>When an exception occurs in the <code>try<\/code> block, the control of the program immediately jumps to the <code>catch<\/code> block.<\/p>\n\n\n\n<p>The following program shows how to use the <code>try...catch<\/code> statement to handle the 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\">int<\/span> amount = <span class=\"hljs-number\">100<\/span>;\n<span class=\"hljs-keyword\">int<\/span> qty = <span class=\"hljs-number\">0<\/span>;\n\n<span class=\"hljs-keyword\">try<\/span>\n{\n    <span class=\"hljs-keyword\">int<\/span> result = amount \/ qty;\n    Console.WriteLine(result);\n}\n<span class=\"hljs-keyword\">catch<\/span>\n{\n    Console.WriteLine(<span class=\"hljs-string\">\"The program was terminated due to an error.\"<\/span>);\n}\n\nConsole.WriteLine(<span class=\"hljs-string\">\"Bye!\"<\/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>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\">The program was terminated due to an error.\nBye!<\/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<p>In this program, the <code>DivideByZeroException<\/code> exception occurred that caused the <code>catch<\/code> block to be executed and showed the error message. The program ran without crashing.<\/p>\n\n\n\n<p>If you know the exact type of exception, you can specify it in the <code>catch<\/code> block. For example:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-6\" data-shcb-language-name=\"C#\" data-shcb-language-slug=\"cs\"><span><code class=\"hljs language-cs\"><span class=\"hljs-keyword\">int<\/span> amount = <span class=\"hljs-number\">100<\/span>;\n<span class=\"hljs-keyword\">int<\/span> qty = <span class=\"hljs-number\">0<\/span>;\n\n<span class=\"hljs-keyword\">try<\/span>\n{\n    <span class=\"hljs-keyword\">int<\/span> result = amount \/ qty;\n    Console.WriteLine(result);\n}\n<span class=\"hljs-keyword\">catch<\/span>(DivideByZeroException e)\n{\n    Console.WriteLine(<span class=\"hljs-string\">\"The program was terminated due to an error.\"<\/span>);\n    Console.WriteLine(<span class=\"hljs-string\">$\"Message: <span class=\"hljs-subst\">{e.Message}<\/span>\"<\/span>);\n    Console.WriteLine(<span class=\"hljs-string\">$\"Source: <span class=\"hljs-subst\">{e.Source}<\/span>\"<\/span>);\n    Console.WriteLine(<span class=\"hljs-string\">$\"Stack: <span class=\"hljs-subst\">{e.StackTrace}<\/span>\"<\/span>);\n}\n\nConsole.WriteLine(<span class=\"hljs-string\">\"Bye!\"<\/span>);<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-6\"><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>Output:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-7\" data-shcb-language-name=\"C#\" data-shcb-language-slug=\"cs\"><span><code class=\"hljs language-cs\">The program was terminated due to an error.\nMessage: Attempted to divide <span class=\"hljs-keyword\">by<\/span> zero.\nSource: Program\nStack:    at Program.&lt;Main&gt;$(String&#91;] args) <span class=\"hljs-keyword\">in<\/span> D:\\csharp\\Program.cs:line <span class=\"hljs-number\">6<\/span>\nBye!<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-7\"><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>In this example, the catch block caught the <code>DivideByZeroException<\/code> exception and assigned an instance to the <code>e<\/code> variable. The <code>DivideByZeroException<\/code> object (<code>e<\/code>) has detailed information about the exception such as:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><code>Message<\/code> &#8211; contains the error message that explains the cause of the exception.<\/li>\n\n\n\n<li><code>Source<\/code> &#8211; contains the name of the assembly where the exception originated.<\/li>\n\n\n\n<li><code>StackTrace<\/code> &#8211; describes where the exception occurred.<\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\">Exception types<\/h2>\n\n\n\n<p>C# defines many exception classes, each representing a specific type. All exception classes are derived from the <code>System.Exception<\/code> class, which in turn is derived from the <code>System.Object<\/code> class.<\/p>\n\n\n\n<p>The following picture illustrates the exception hierarchy:<\/p>\n\n\n\n<figure class=\"wp-block-image size-full\"><img decoding=\"async\" src=\"https:\/\/csharptutorial.net\/wp-content\/uploads\/2022\/05\/c-try-catch.svg\" alt=\"\" class=\"wp-image-663\"\/><\/figure>\n\n\n\n<h2 class=\"wp-block-heading\">More on the catch clause<\/h2>\n\n\n\n<p>The <code>catch<\/code> clause handles exceptions. It has four forms.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">1) General catch clause<\/h3>\n\n\n\n<p>The general <code>catch<\/code> clause does not have a parameter list of the <code>catch<\/code> keyword. It matches any exception raised in the <code>try<\/code> block:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-8\" data-shcb-language-name=\"C#\" data-shcb-language-slug=\"cs\"><span><code class=\"hljs language-cs\"><span class=\"hljs-keyword\">try<\/span>\n{ \n}\n<span class=\"hljs-keyword\">catch<\/span>\n{\n}<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-8\"><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<h3 class=\"wp-block-heading\">2) Specific catch clause<\/h3>\n\n\n\n<p>A specific <code>catch<\/code> clause specifies the name of an exception class as a single parameter. It matches any exception with the name that matches the parameter:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-9\" data-shcb-language-name=\"C#\" data-shcb-language-slug=\"cs\"><span><code class=\"hljs language-cs\"><span class=\"hljs-keyword\">try<\/span>\n{\n    <span class=\"hljs-comment\">\/\/ statement<\/span>\n}\n<span class=\"hljs-keyword\">catch<\/span> (ExceptionType)\n{\n    <span class=\"hljs-comment\">\/\/ handle exception with the ExceptionType<\/span>\n}<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-9\"><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<h3 class=\"wp-block-heading\">3) Specific catch clause with object<\/h3>\n\n\n\n<p>The specific <code>catch<\/code> clause with an object includes an exception variable after the name of the exception class. This exception variable references the exception object. By using an exception variable, you can access specific information about the exception.<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-10\" data-shcb-language-name=\"C#\" data-shcb-language-slug=\"cs\"><span><code class=\"hljs language-cs\"><span class=\"hljs-keyword\">try<\/span>\n{\n    <span class=\"hljs-comment\">\/\/ statement<\/span>\n}\n<span class=\"hljs-keyword\">catch<\/span> (ExceptionType e)\n{\n    <span class=\"hljs-comment\">\/\/ handle exception with the ExceptionType<\/span>\n}<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-10\"><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<h3 class=\"wp-block-heading\">4) Specific catch with a predicate<\/h3>\n\n\n\n<p>The specific catch is like a specific <code>catch<\/code> with an object but also includes a predicate. The <code>catch<\/code> will execute only if the condition in the predicate is <code>true<\/code>:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-11\" data-shcb-language-name=\"C#\" data-shcb-language-slug=\"cs\"><span><code class=\"hljs language-cs\"><span class=\"hljs-keyword\">try<\/span>\n{\n    <span class=\"hljs-comment\">\/\/ statement<\/span>\n}\n<span class=\"hljs-keyword\">catch<\/span> (ExceptionType e) <span class=\"hljs-keyword\">where<\/span> (predicate)\n{\n    <span class=\"hljs-comment\">\/\/ handle exception with the ExceptionType<\/span>\n}<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-11\"><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>Exceptions are runtime errors that occurred in the program.<\/li>\n\n\n\n<li>Use the <code>try...catch<\/code> statement 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=\"661\"\n\t\t\t\tdata-post-url=\"https:\/\/www.csharptutorial.net\/csharp-tutorial\/csharp-try-catch\/\"\n\t\t\t\tdata-post-title=\"C# try catch\"\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=\"661\"\n\t\t\t\tdata-post-url=\"https:\/\/www.csharptutorial.net\/csharp-tutorial\/csharp-try-catch\/\"\n\t\t\t\tdata-post-title=\"C# try catch\"\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 about exceptions and how to use the C# try&#8230;catch statement to handle exceptions. Introduction to the C# try catch statement Exceptions are runtime errors in a program, which violate system constraints. For example, when the program attempts to divide a number by zero, an exception occurs. When an exception [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"parent":7,"menu_order":58,"comment_status":"closed","ping_status":"closed","template":"","meta":{"footnotes":""},"class_list":["post-661","page","type-page","status-publish","hentry"],"_links":{"self":[{"href":"https:\/\/www.csharptutorial.net\/wp-json\/wp\/v2\/pages\/661","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=661"}],"version-history":[{"count":5,"href":"https:\/\/www.csharptutorial.net\/wp-json\/wp\/v2\/pages\/661\/revisions"}],"predecessor-version":[{"id":1353,"href":"https:\/\/www.csharptutorial.net\/wp-json\/wp\/v2\/pages\/661\/revisions\/1353"}],"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=661"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}