{"id":1377,"date":"2023-04-04T11:16:59","date_gmt":"2023-04-04T04:16:59","guid":{"rendered":"https:\/\/csharptutorial.net\/?page_id=1377"},"modified":"2023-04-04T11:17:01","modified_gmt":"2023-04-04T04:17:01","slug":"csharp-throw-exception","status":"publish","type":"page","link":"https:\/\/www.csharptutorial.net\/csharp-tutorial\/csharp-throw-exception\/","title":{"rendered":"C# throw"},"content":{"rendered":"\n<p><strong>Summary<\/strong>: in this tutorial, you&#8217;ll learn how to use the C# <code>throw<\/code> keyword to raise an exception in your application.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Introduction to the C# throw keyword<\/h2>\n\n\n\n<p>The <code>throw<\/code> keyword allows you to raise an exception. Here&#8217;s the syntax of how to use the <code>throw<\/code> keyword: <\/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\">throw<\/span> exception;<\/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 syntax, the <code>exception<\/code> is an object that represents the exception that you want to raise. You can use any built-in exception class that is derived from the <code>System.Exception<\/code> class. Also, you can <a href=\"https:\/\/csharptutorial.net\/csharp-tutorial\/csharp-custom-exceptions\/\">raise a custom exception<\/a>, which will cover in the next tutorial.<\/p>\n\n\n\n<p>Typically, you use the <code>throw<\/code> keyword with an <code><a href=\"https:\/\/csharptutorial.net\/csharp-tutorial\/csharp-if\/\">if<\/a><\/code> statement to throw an exception once a certain condition is met:<\/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-keyword\">if<\/span> (condition)\r\n{\r\n    <span class=\"hljs-keyword\">throw<\/span> exception;\r\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<h2 class=\"wp-block-heading\">Using the C# throw keyword to raise an exception example<\/h2>\n\n\n\n<p>The following program demonstrates how to use the <code>throw<\/code> keyword to throw an <code>ArgumentOutOfRangeException<\/code> exception:<\/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\">using<\/span> <span class=\"hljs-keyword\">static<\/span> System.Console;\r\n\r\n<span class=\"hljs-keyword\">public<\/span> <span class=\"hljs-keyword\">class<\/span> <span class=\"hljs-title\">Circle<\/span>\r\n{\r\n    <span class=\"hljs-keyword\">public<\/span> <span class=\"hljs-keyword\">double<\/span> Radius\r\n    {\r\n        <span class=\"hljs-keyword\">get<\/span>; <span class=\"hljs-keyword\">set<\/span>;\r\n    }\r\n    <span class=\"hljs-function\"><span class=\"hljs-keyword\">public<\/span> <span class=\"hljs-title\">Circle<\/span>(<span class=\"hljs-params\"><span class=\"hljs-keyword\">double<\/span> radius<\/span>)<\/span>\r\n    {\r\n        <span class=\"hljs-keyword\">if<\/span> (radius &lt;= <span class=\"hljs-number\">0<\/span>)\r\n        {\r\n            <span class=\"hljs-keyword\">throw<\/span> <span class=\"hljs-keyword\">new<\/span> ArgumentOutOfRangeException(\r\n                 <span class=\"hljs-keyword\">nameof<\/span>(radius),\r\n                <span class=\"hljs-string\">\"The radius should be positive\"<\/span>\r\n             );\r\n        }\r\n        Radius = radius;\r\n    }\r\n    <span class=\"hljs-function\"><span class=\"hljs-keyword\">public<\/span> <span class=\"hljs-keyword\">double<\/span> <span class=\"hljs-title\">GetArea<\/span>(<span class=\"hljs-params\"><\/span>)<\/span> =&gt; Math.PI * Radius * Radius;\r\n\r\n}\r\n\r\n<span class=\"hljs-keyword\">class<\/span> <span class=\"hljs-title\">Program<\/span>\r\n{\r\n    <span class=\"hljs-function\"><span class=\"hljs-keyword\">public<\/span> <span class=\"hljs-keyword\">static<\/span> <span class=\"hljs-keyword\">void<\/span> <span class=\"hljs-title\">Main<\/span>(<span class=\"hljs-params\"><span class=\"hljs-keyword\">string<\/span>&#91;] args<\/span>)<\/span>\r\n    {\r\n        WriteLine(<span class=\"hljs-string\">\"Enter a radius:\"<\/span>);\r\n        <span class=\"hljs-keyword\">var<\/span> input = ReadLine();\r\n        <span class=\"hljs-keyword\">if<\/span> (input != <span class=\"hljs-literal\">null<\/span>)\r\n        {\r\n            <span class=\"hljs-keyword\">var<\/span> radius = <span class=\"hljs-keyword\">double<\/span>.Parse(input);\r\n            <span class=\"hljs-keyword\">try<\/span>\r\n            {\r\n                <span class=\"hljs-keyword\">var<\/span> circle = <span class=\"hljs-keyword\">new<\/span> Circle(radius);\r\n                WriteLine(<span class=\"hljs-string\">$\"The area is <span class=\"hljs-subst\">{circle.GetArea():F2}<\/span>\"<\/span>);\r\n            }\r\n            <span class=\"hljs-keyword\">catch<\/span> (ArgumentOutOfRangeException ex)\r\n            {\r\n                WriteLine(ex.Message);\r\n            }\r\n\r\n        }\r\n    }\r\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>How it works.<\/p>\n\n\n\n<p>First, define a class called <code>Circle<\/code> that represents a circle with a given radius. <\/p>\n\n\n\n<p>In the <code>Circle<\/code> class, we define a constructor that takes a <code>double<\/code> value representing the radius of the circle. If the value of the radius is less than or equal to zero, we throw an <code>ArgumentOutOfRangeException<\/code> with a custom error message using the <code>throw<\/code> keyword.<\/p>\n\n\n\n<p>In the <code>Circle<\/code> class, we also define a method <code>GetArea()<\/code> that returns the area of the circle using the formula \u03c0r\u00b2.<\/p>\n\n\n\n<p>Second, prompt the user to enter a radius in the <code>Main<\/code> method of the program.  <\/p>\n\n\n\n<p>The <code>Main()<\/code> method:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Reads the input from the console  <\/li>\n\n\n\n<li>Parses it to a <code>double<\/code> <\/li>\n\n\n\n<li>Creates an instance of the <code>Circle<\/code> class with the entered radius value <\/li>\n\n\n\n<li>Calls the <code>GetArea()<\/code> method to calculate the area of the circle. <\/li>\n<\/ul>\n\n\n\n<p>If the entered radius is not positive, the <code>Main<\/code> method catches the <code>ArgumentOutOfRangeException<\/code> exception raised by the constructor and displays the error message on the console.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">The throw Expression<\/h2>\n\n\n\n<p>Starting from C# 7.0, you can use the <code>throw<\/code> keyword as an expression. This allows you to throw an exception inline, without having to define a separate variable. The syntax of the <code>throw<\/code> expression is as follows:<\/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\"><span class=\"hljs-keyword\">throw<\/span> expression;<\/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 syntax, the <code>expression<\/code> evaluates to an object derived from the <code>System.Exception<\/code> class. For example, you can change the <code>Circle<\/code> constructor in the previous example to the following:<\/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\"><span class=\"hljs-function\"><span class=\"hljs-keyword\">public<\/span> <span class=\"hljs-title\">Circle<\/span>(<span class=\"hljs-params\"><span class=\"hljs-keyword\">double<\/span> radius<\/span>)<\/span>\r\n{\r\n    Radius = radius &gt; <span class=\"hljs-number\">0<\/span>\r\n                ? radius\r\n                : <span class=\"hljs-keyword\">throw<\/span> <span class=\"hljs-keyword\">new<\/span> ArgumentOutOfRangeException(\r\n                    <span class=\"hljs-keyword\">nameof<\/span>(radius),\r\n                    <span class=\"hljs-string\">\"The radius should be positive\"<\/span>\r\n                  );\r\n}<\/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 example, if the <code>radius<\/code> is greater than zero, we assign it to the <code>Radius<\/code> property. Otherwise, we throw the <code>ArgumentOutOfRangeException<\/code> exception. This has the same effect as the previous example but is more concise.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Summary<\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Use the C# <code>throw<\/code> keyword to raise an exception explicitly.<\/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=\"1377\"\n\t\t\t\tdata-post-url=\"https:\/\/www.csharptutorial.net\/csharp-tutorial\/csharp-throw-exception\/\"\n\t\t\t\tdata-post-title=\"C# throw\"\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=\"1377\"\n\t\t\t\tdata-post-url=\"https:\/\/www.csharptutorial.net\/csharp-tutorial\/csharp-throw-exception\/\"\n\t\t\t\tdata-post-title=\"C# throw\"\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>In this tutorial, you&#8217;ll learn how to use the throw keyword to raise an exception in your application.<\/p>\n","protected":false},"author":1,"featured_media":0,"parent":7,"menu_order":60,"comment_status":"closed","ping_status":"closed","template":"","meta":{"footnotes":""},"class_list":["post-1377","page","type-page","status-publish","hentry"],"_links":{"self":[{"href":"https:\/\/www.csharptutorial.net\/wp-json\/wp\/v2\/pages\/1377","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=1377"}],"version-history":[{"count":2,"href":"https:\/\/www.csharptutorial.net\/wp-json\/wp\/v2\/pages\/1377\/revisions"}],"predecessor-version":[{"id":1379,"href":"https:\/\/www.csharptutorial.net\/wp-json\/wp\/v2\/pages\/1377\/revisions\/1379"}],"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=1377"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}