{"id":131,"date":"2022-07-11T06:59:32","date_gmt":"2022-07-11T06:59:32","guid":{"rendered":"https:\/\/valerio.nu\/?p=131"},"modified":"2022-07-11T06:59:33","modified_gmt":"2022-07-11T06:59:33","slug":"the-java-arithmetic-exception-what-it-is-and-how-to-avoid-triggering-it","status":"publish","type":"post","link":"https:\/\/valerio.nu\/index.php\/2022\/07\/11\/the-java-arithmetic-exception-what-it-is-and-how-to-avoid-triggering-it\/","title":{"rendered":"The Java Arithmetic Exception: what it is and how to avoid triggering it"},"content":{"rendered":"\n<p>In this tutorial, we are going to write about ArithmeticException in Java, when it occurs and how to handle it.<\/p>\n\n\n\n<p>ArithmeticException is an that happens at runtime; it is thrown when an exceptional arithmetic condition has occurred. The result of that is the Java Virtual Machine throwing a runtime exception because it can\u2019t deal mathematically with the case at hand.<\/p>\n\n\n\n<p>There are two main situations that lead to ArithmeticException:<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li>Dividing number by 0<\/li><li>Using BigDecimal with infinite decimal representation<\/li><\/ul>\n\n\n\n<p><strong>Dividing a number by 0<\/strong> (integer zero) is a mathematically wrong operation, the result is undefined. It is possible to write code that might lead to that situation, for example:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>public static void main(String&#91;] args) {\r\n\r\n    System.out.println(\"Enter two numbers to divide them : a\/b \");\r\n\r    Scanner input = new Scanner(System.in);\r\n\r\n    int a = input.nextInt();\r\n    int b = input.nextInt();\r\n\r\n    int result = a\/b;\r\n\r\n    System.out.println(result);\r\n\r\n}\r\n<\/code><\/pre>\n\n\n\n<p>In the code above, we are asking the user to: enter two numbers, divide them and then print the result. Here the user can input anything, so if they enter &#8220;0&#8221; as denominator the program will throw an ArithmeticException. <\/p>\n\n\n\n<p>We would then see something like the following in the standard output: <\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>Enter two numbers to divide them : a\/b\r\n    3\r\n    0\r\n    Exception in thread \"main\" java.lang.ArithmeticException: \/ by zero\r\n    at test.c1Test.main(c1Test.java:18)\n<\/code><\/pre>\n\n\n\n<p>The other case that leads to ArithmeticException is <strong>using a BigDecimal with infinite decimal representation<\/strong>.<\/p>\n\n\n\n<p>Developers use BigDecimal to represent long decimal values since the type can contain 32 bit on an integer scale. It has quite a high precision. However, in the specific case when the decimal has an infinite series of digits, BigDecimal doesn&#8217;t have enough space to store the series. Let\u2019s see the following example:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>public static void main(String&#91;] args) {\r\n\r\n    System.out.println(\"Enter two numbers to divide them : a\/b \");\r\n\r    Scanner input = new Scanner(System.in);\r\n\r\n    Double a = input.nextDouble();\r\n    Double b = input.nextDouble();\r\n    BigDecimal decimal1 = new BigDecimal(a);\r\n    BigDecimal decimal2 = new BigDecimal(b);\r\n\r\n    decimal1 = decimal1.divide(decimal2);\r\n\r\n    System.out.println(decimal1.toString());\r\n\r\n}\r\n<\/code><\/pre>\n\n\n\n<p>The above example is again asking the user two double values to divide the first by the second. Once the user enters the numbers, the code assigns these values to BigDecimal variables. To divide in BigDecimal we use the method .divide(), then we print the result. Let\u2019s suppose that the user entered 1 and 7; that would produce a very long decimal representation and here&#8217;s how the language deals with it: <\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>Enter two numbers to divide them : a\/b \r\n1\r\n7\r\n    Exception in thread \"main\" java.lang.ArithmeticException: Non-terminating decimal expansion; no exact representable decimal result.\r\n    at java.math.BigDecimal.divide(BigDecimal.java:1693)\r\n    at test.c1Test.main(c1Test.java:21)\r\n<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">How to handle the ArithmeticException?<\/h3>\n\n\n\n<p>Like any other exception in Java, developers can handle the ArithmeticException to ensure the program will not break when that happens. By using the <strong>try-catch<\/strong> block developers can handle this exception the way they want, let\u2019s bring back the first example and handle it:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>public static void main(String&#91;] args) {\r\n    try {\r\n\r\n        System.out.println(\"Enter two numbers to divide them : a\/b \");\r\n\r        Scanner input = new Scanner(System.in);\r\n\r\n        int a = input.nextInt();\r\n        int b = input.nextInt();\r\n\r\n        int result = a \/ b;\r\n\r\n        System.out.println(result);\r\n\r\n    } catch (ArithmeticException exception) {\r\n        System.out.println(\"You cannot divide a number by 0!\");\r\n    }\r\n}\r\n<\/code><\/pre>\n\n\n\n<p>If the user enter &#8220;0&#8221; as the second number then the ArithmeticException will be handled by printing an error message that explains the situation.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>Enter two numbers to divide them : a\/b\r\n    3\r\n    0\r\n    You cannot divide number by 0 ! \n\n<\/code><\/pre>\n","protected":false},"excerpt":{"rendered":"<p>In this tutorial, we are going to write about ArithmeticException in Java, when it occurs and how to handle it. ArithmeticException is an that happens [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[11],"tags":[],"class_list":["post-131","post","type-post","status-publish","format-standard","hentry","category-java"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v27.5 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\n<title>The Java Arithmetic Exception: what it is and how to avoid triggering it - Andy&#039;s blog \u2935\ufe0f<\/title>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/valerio.nu\/index.php\/2022\/07\/11\/the-java-arithmetic-exception-what-it-is-and-how-to-avoid-triggering-it\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"The Java Arithmetic Exception: what it is and how to avoid triggering it - Andy&#039;s blog \u2935\ufe0f\" \/>\n<meta property=\"og:description\" content=\"In this tutorial, we are going to write about ArithmeticException in Java, when it occurs and how to handle it. ArithmeticException is an that happens [&hellip;]\" \/>\n<meta property=\"og:url\" content=\"https:\/\/valerio.nu\/index.php\/2022\/07\/11\/the-java-arithmetic-exception-what-it-is-and-how-to-avoid-triggering-it\/\" \/>\n<meta property=\"og:site_name\" content=\"Andy&#039;s blog \u2935\ufe0f\" \/>\n<meta property=\"article:published_time\" content=\"2022-07-11T06:59:32+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2022-07-11T06:59:33+00:00\" \/>\n<meta name=\"author\" content=\"andy\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"andy\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"3 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\\\/\\\/schema.org\",\"@graph\":[{\"@type\":\"Article\",\"@id\":\"https:\\\/\\\/valerio.nu\\\/index.php\\\/2022\\\/07\\\/11\\\/the-java-arithmetic-exception-what-it-is-and-how-to-avoid-triggering-it\\\/#article\",\"isPartOf\":{\"@id\":\"https:\\\/\\\/valerio.nu\\\/index.php\\\/2022\\\/07\\\/11\\\/the-java-arithmetic-exception-what-it-is-and-how-to-avoid-triggering-it\\\/\"},\"author\":{\"name\":\"andy\",\"@id\":\"https:\\\/\\\/valerio.nu\\\/#\\\/schema\\\/person\\\/da69cc3da309893b0d3bc8fcef75f128\"},\"headline\":\"The Java Arithmetic Exception: what it is and how to avoid triggering it\",\"datePublished\":\"2022-07-11T06:59:32+00:00\",\"dateModified\":\"2022-07-11T06:59:33+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\\\/\\\/valerio.nu\\\/index.php\\\/2022\\\/07\\\/11\\\/the-java-arithmetic-exception-what-it-is-and-how-to-avoid-triggering-it\\\/\"},\"wordCount\":382,\"commentCount\":0,\"articleSection\":[\"Java\"],\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"CommentAction\",\"name\":\"Comment\",\"target\":[\"https:\\\/\\\/valerio.nu\\\/index.php\\\/2022\\\/07\\\/11\\\/the-java-arithmetic-exception-what-it-is-and-how-to-avoid-triggering-it\\\/#respond\"]}]},{\"@type\":\"WebPage\",\"@id\":\"https:\\\/\\\/valerio.nu\\\/index.php\\\/2022\\\/07\\\/11\\\/the-java-arithmetic-exception-what-it-is-and-how-to-avoid-triggering-it\\\/\",\"url\":\"https:\\\/\\\/valerio.nu\\\/index.php\\\/2022\\\/07\\\/11\\\/the-java-arithmetic-exception-what-it-is-and-how-to-avoid-triggering-it\\\/\",\"name\":\"The Java Arithmetic Exception: what it is and how to avoid triggering it - Andy&#039;s blog \u2935\ufe0f\",\"isPartOf\":{\"@id\":\"https:\\\/\\\/valerio.nu\\\/#website\"},\"datePublished\":\"2022-07-11T06:59:32+00:00\",\"dateModified\":\"2022-07-11T06:59:33+00:00\",\"author\":{\"@id\":\"https:\\\/\\\/valerio.nu\\\/#\\\/schema\\\/person\\\/da69cc3da309893b0d3bc8fcef75f128\"},\"breadcrumb\":{\"@id\":\"https:\\\/\\\/valerio.nu\\\/index.php\\\/2022\\\/07\\\/11\\\/the-java-arithmetic-exception-what-it-is-and-how-to-avoid-triggering-it\\\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\\\/\\\/valerio.nu\\\/index.php\\\/2022\\\/07\\\/11\\\/the-java-arithmetic-exception-what-it-is-and-how-to-avoid-triggering-it\\\/\"]}]},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\\\/\\\/valerio.nu\\\/index.php\\\/2022\\\/07\\\/11\\\/the-java-arithmetic-exception-what-it-is-and-how-to-avoid-triggering-it\\\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\\\/\\\/valerio.nu\\\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"The Java Arithmetic Exception: what it is and how to avoid triggering it\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\\\/\\\/valerio.nu\\\/#website\",\"url\":\"https:\\\/\\\/valerio.nu\\\/\",\"name\":\"Andy&#039;s blog \u2935\ufe0f\",\"description\":\"Abandon all hope, ye who enter here\",\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\\\/\\\/valerio.nu\\\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"},{\"@type\":\"Person\",\"@id\":\"https:\\\/\\\/valerio.nu\\\/#\\\/schema\\\/person\\\/da69cc3da309893b0d3bc8fcef75f128\",\"name\":\"andy\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\\\/\\\/secure.gravatar.com\\\/avatar\\\/4852a025c6250c852814d4017f646677730a23c1ec14eb5ca36b69dcce5135a5?s=96&d=mm&r=g\",\"url\":\"https:\\\/\\\/secure.gravatar.com\\\/avatar\\\/4852a025c6250c852814d4017f646677730a23c1ec14eb5ca36b69dcce5135a5?s=96&d=mm&r=g\",\"contentUrl\":\"https:\\\/\\\/secure.gravatar.com\\\/avatar\\\/4852a025c6250c852814d4017f646677730a23c1ec14eb5ca36b69dcce5135a5?s=96&d=mm&r=g\",\"caption\":\"andy\"},\"sameAs\":[\"https:\\\/\\\/valerio.nu\"],\"url\":\"https:\\\/\\\/valerio.nu\\\/index.php\\\/author\\\/giuseppe\\\/\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"The Java Arithmetic Exception: what it is and how to avoid triggering it - Andy&#039;s blog \u2935\ufe0f","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/valerio.nu\/index.php\/2022\/07\/11\/the-java-arithmetic-exception-what-it-is-and-how-to-avoid-triggering-it\/","og_locale":"en_US","og_type":"article","og_title":"The Java Arithmetic Exception: what it is and how to avoid triggering it - Andy&#039;s blog \u2935\ufe0f","og_description":"In this tutorial, we are going to write about ArithmeticException in Java, when it occurs and how to handle it. ArithmeticException is an that happens [&hellip;]","og_url":"https:\/\/valerio.nu\/index.php\/2022\/07\/11\/the-java-arithmetic-exception-what-it-is-and-how-to-avoid-triggering-it\/","og_site_name":"Andy&#039;s blog \u2935\ufe0f","article_published_time":"2022-07-11T06:59:32+00:00","article_modified_time":"2022-07-11T06:59:33+00:00","author":"andy","twitter_card":"summary_large_image","twitter_misc":{"Written by":"andy","Est. reading time":"3 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/valerio.nu\/index.php\/2022\/07\/11\/the-java-arithmetic-exception-what-it-is-and-how-to-avoid-triggering-it\/#article","isPartOf":{"@id":"https:\/\/valerio.nu\/index.php\/2022\/07\/11\/the-java-arithmetic-exception-what-it-is-and-how-to-avoid-triggering-it\/"},"author":{"name":"andy","@id":"https:\/\/valerio.nu\/#\/schema\/person\/da69cc3da309893b0d3bc8fcef75f128"},"headline":"The Java Arithmetic Exception: what it is and how to avoid triggering it","datePublished":"2022-07-11T06:59:32+00:00","dateModified":"2022-07-11T06:59:33+00:00","mainEntityOfPage":{"@id":"https:\/\/valerio.nu\/index.php\/2022\/07\/11\/the-java-arithmetic-exception-what-it-is-and-how-to-avoid-triggering-it\/"},"wordCount":382,"commentCount":0,"articleSection":["Java"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/valerio.nu\/index.php\/2022\/07\/11\/the-java-arithmetic-exception-what-it-is-and-how-to-avoid-triggering-it\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/valerio.nu\/index.php\/2022\/07\/11\/the-java-arithmetic-exception-what-it-is-and-how-to-avoid-triggering-it\/","url":"https:\/\/valerio.nu\/index.php\/2022\/07\/11\/the-java-arithmetic-exception-what-it-is-and-how-to-avoid-triggering-it\/","name":"The Java Arithmetic Exception: what it is and how to avoid triggering it - Andy&#039;s blog \u2935\ufe0f","isPartOf":{"@id":"https:\/\/valerio.nu\/#website"},"datePublished":"2022-07-11T06:59:32+00:00","dateModified":"2022-07-11T06:59:33+00:00","author":{"@id":"https:\/\/valerio.nu\/#\/schema\/person\/da69cc3da309893b0d3bc8fcef75f128"},"breadcrumb":{"@id":"https:\/\/valerio.nu\/index.php\/2022\/07\/11\/the-java-arithmetic-exception-what-it-is-and-how-to-avoid-triggering-it\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/valerio.nu\/index.php\/2022\/07\/11\/the-java-arithmetic-exception-what-it-is-and-how-to-avoid-triggering-it\/"]}]},{"@type":"BreadcrumbList","@id":"https:\/\/valerio.nu\/index.php\/2022\/07\/11\/the-java-arithmetic-exception-what-it-is-and-how-to-avoid-triggering-it\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/valerio.nu\/"},{"@type":"ListItem","position":2,"name":"The Java Arithmetic Exception: what it is and how to avoid triggering it"}]},{"@type":"WebSite","@id":"https:\/\/valerio.nu\/#website","url":"https:\/\/valerio.nu\/","name":"Andy&#039;s blog \u2935\ufe0f","description":"Abandon all hope, ye who enter here","potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/valerio.nu\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Person","@id":"https:\/\/valerio.nu\/#\/schema\/person\/da69cc3da309893b0d3bc8fcef75f128","name":"andy","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/secure.gravatar.com\/avatar\/4852a025c6250c852814d4017f646677730a23c1ec14eb5ca36b69dcce5135a5?s=96&d=mm&r=g","url":"https:\/\/secure.gravatar.com\/avatar\/4852a025c6250c852814d4017f646677730a23c1ec14eb5ca36b69dcce5135a5?s=96&d=mm&r=g","contentUrl":"https:\/\/secure.gravatar.com\/avatar\/4852a025c6250c852814d4017f646677730a23c1ec14eb5ca36b69dcce5135a5?s=96&d=mm&r=g","caption":"andy"},"sameAs":["https:\/\/valerio.nu"],"url":"https:\/\/valerio.nu\/index.php\/author\/giuseppe\/"}]}},"_links":{"self":[{"href":"https:\/\/valerio.nu\/index.php\/wp-json\/wp\/v2\/posts\/131","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/valerio.nu\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/valerio.nu\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/valerio.nu\/index.php\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/valerio.nu\/index.php\/wp-json\/wp\/v2\/comments?post=131"}],"version-history":[{"count":2,"href":"https:\/\/valerio.nu\/index.php\/wp-json\/wp\/v2\/posts\/131\/revisions"}],"predecessor-version":[{"id":133,"href":"https:\/\/valerio.nu\/index.php\/wp-json\/wp\/v2\/posts\/131\/revisions\/133"}],"wp:attachment":[{"href":"https:\/\/valerio.nu\/index.php\/wp-json\/wp\/v2\/media?parent=131"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/valerio.nu\/index.php\/wp-json\/wp\/v2\/categories?post=131"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/valerio.nu\/index.php\/wp-json\/wp\/v2\/tags?post=131"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}