{"id":88614,"date":"2023-10-20T19:00:19","date_gmt":"2023-10-20T13:30:19","guid":{"rendered":"https:\/\/techvidvan.com\/tutorials\/?p=88614"},"modified":"2023-10-20T19:00:19","modified_gmt":"2023-10-20T13:30:19","slug":"java-try-catch-block","status":"publish","type":"post","link":"https:\/\/techvidvan.com\/tutorials\/java-try-catch-block\/","title":{"rendered":"Java Try Catch Block"},"content":{"rendered":"<p>In Java, try-catch block is used for exception handling. Allowing us to handle and manage runtime exceptions. The try block&#8217;s remaining statements won&#8217;t run if an exception arises at that specific statement. Therefore, it is advised against keeping code in a try block that won&#8217;t throw an exception.<\/p>\n<p>Java try blocks must be followed by a finally block or a catch.<\/p>\n<p><strong>The basic structure of the try-catch block will look like this:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">try {\n\/\/ block of code to try\n   } \ncatch (Exception e1) {\n\/\/ block of code to handle errors\n    }<\/pre>\n<h2>Try block<\/h2>\n<ul>\n<li>The try block allows us to define a block of code that you want to monitor for exception.<\/li>\n<li>If an exception occurs within this block, the control will be transferred to the appropriate catch block.<\/li>\n<\/ul>\n<h3>Catch block<\/h3>\n<ul>\n<li>The particular sort of exception is caught and handled using the catch block.<\/li>\n<li>We can use multiple catch blocks within a try block.<\/li>\n<li>It is used to handle different types of exceptions within the try block.<\/li>\n<\/ul>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">try {\n\/\/ block of code to try\n}\ncatch(exception e1 {\n\/\/ block of code to be handle\n}\ncatch(Exception e2)\n{\n\/\/ block of code to be handle\n}<\/pre>\n<p><a href=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2023\/09\/Catch-block.webp\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-88757\" src=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2023\/09\/Catch-block.webp\" alt=\"Catch block \" width=\"500\" height=\"367\" \/><\/a><\/p>\n<h3>Blocks and Exception Handling Keywords<\/h3>\n<h4>try:<\/h4>\n<p>There are a number of statements in the try block where an exception might arise.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">try\n\/\/ Statement(s) that could lead to an exception<\/pre>\n<h4>catch:<\/h4>\n<p>The catch block is used to manage a try block&#8217;s ambiguous condition. A catch block, which deals with the exception that arises in the related try block, is always placed after a try block.<\/p>\n<p>close a connection, close a file, and leave the process after writing details to a log file are some instances of catch statements that handle exceptions.<\/p>\n<h4>throw:<\/h4>\n<p>Control is moved from the try block to the catch block using the throw keyword.<\/p>\n<h4>throws:<\/h4>\n<p>When handling exceptions without the use of a try-and-catch block, this keyword is used. It does not handle the exceptions that a method can throw to the caller; it only specifies them.<\/p>\n<h4>finally:<\/h4>\n<p>It is carried out following the catch block. When there are several catch blocks, we use it to place some common code (to be performed whether an error has happened or not).<\/p>\n<p><strong>Example<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">public class DataFlair\n{\n    public static void main(String[] args) {\n        try{\n        int data = 10\/0;\n        System.out.println(data);\n        }\n        catch(Exception e){\n            System.out.println(\"Something went wrong\");\n        }\n            \n        }\n        \n    }<\/pre>\n<p><strong>Output<\/strong><\/p>\n<p>Something went wrong<\/p>\n<p>In this example, the divide method attempts to divide two integers. Since division by zero is not allowed, an ArithmeticException is thrown. The try-catch block catches this exception and prints an error message, and the finally block prints a message indicating its execution.<\/p>\n<p>In Java, a try block can be used in place of a catch block. But without a try block, we are unable to employ a catch block.<\/p>\n<h3>Internal Working of Java try-catch block:<\/h3>\n<p><a href=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2023\/09\/Internal-Working-of-Java-try-catch-block.webp\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-88782\" src=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2023\/09\/Internal-Working-of-Java-try-catch-block.webp\" alt=\"Internal-Working-of-Java \" width=\"500\" height=\"314\" \/><\/a><\/p>\n<h4>Problem without Exception Handling<\/h4>\n<p><strong>Example 1<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">public class TryCatchExample1 {  \n    public static void main(String[] args) {      \n        int data=50\/0; \n        System.out.println(\"rest of the code\");     \n    }     \n}<\/pre>\n<p><strong>Output<\/strong><\/p>\n<p>Exception in thread &#8220;main&#8221; java.lang.ArithmeticException: \/ by zero<\/p>\n<p>The remaining statements in the code are not printed in this scenario, and the remaining code is not run. 100 lines of code could follow the exception. The code below the exception will not run if the exception is not handled.<\/p>\n<h4>Solution by Exception Handling<\/h4>\n<p><strong>Example 2<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">public class TryCatchExample2 { \n    public static void main(String[] args) {  \n        try  \n        {  \n        int data=50\/0; \/\/may throw exception   \n        }  \n        catch(ArithmeticException e)  \n        {  \n            System.out.println(e);  \n        }  \n        System.out.println(\"rest of the code\");  \n    }  \n}<\/pre>\n<p><strong>Output<\/strong><\/p>\n<p>java.lang.ArithmeticException: \/ by zero<\/p>\n<p>rest of the code<\/p>\n<p>The remaining code is executed, resulting in the printing of the remaining code statement, as seen in the example above.<\/p>\n<h4>Java try\u2026..catch block:<\/h4>\n<p><strong>Example<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">class Main {\n  public static void main(String[] args) {\n    try {\n      int divideByZero = 5 \/ 0;\n      System.out.println(\"Rest of code in try block\");\n    }\n    catch (ArithmeticException e) {\n      System.out.println(\"ArithmeticException =&gt; \" + e.getMessage());\n    }\n  }\n}<\/pre>\n<p><strong>Output<\/strong><\/p>\n<p>ArithmeticException =&gt; \/ by zero<\/p>\n<p>We are attempting a division by zero of an integer. There is an exception in this situation. The try block is where we have placed this code as a result. ArithmeticException happens whenever this code is seen by the program. Additionally, the catch block executes the code inside it after catching the exception. Only when there is an exception in the try block is the catch block actually used.<\/p>\n<h4>Java try\u2026.finally block<\/h4>\n<p><strong>Example<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">class Main {\n  public static void main(String[] args) {\n    try {\n      int divideByZero = 5 \/ 0;\n    }\n    finally {\n      System.out.println(\"Finally block is always executed\");\n    }\n  }\n}<\/pre>\n<p><strong>Output<\/strong><\/p>\n<p>Finally block is always executed<\/p>\n<p>Exception in thread &#8220;main&#8221; java.lang.ArithmeticException: \/ by zero<\/p>\n<p>at Main.main(Main.java:4)<\/p>\n<p>Together with the finally block, we have used the try block. We can see that the try block&#8217;s code is resulting in an exception. However, regardless of the exception, the code inside the finally block is run.<\/p>\n<h3>Conclusion<\/h3>\n<p>A try block is a section of code that comprises a number of statements and is used to contain any code that could raise an exception. The catch block, which deals with the exception that arises in the related try block, is always placed after the try block.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>In Java, try-catch block is used for exception handling. Allowing us to handle and manage runtime exceptions. The try block&#8217;s remaining statements won&#8217;t run if an exception arises at that specific statement. Therefore, it&#46;&#46;&#46;<\/p>\n","protected":false},"author":1,"featured_media":88656,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[183],"tags":[296,5229,5230,5231],"class_list":["post-88614","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-java","tag-java","tag-java-try-catch-block","tag-try-catch-block","tag-try-catch-block-in-java"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v27.7 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\n<title>Java Try Catch Block - TechVidvan<\/title>\n<meta name=\"description\" content=\"In Java, try-catch block is used for exception handling. Allowing us to handle and manage runtime exceptions.\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/techvidvan.com\/tutorials\/java-try-catch-block\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Java Try Catch Block - TechVidvan\" \/>\n<meta property=\"og:description\" content=\"In Java, try-catch block is used for exception handling. Allowing us to handle and manage runtime exceptions.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/techvidvan.com\/tutorials\/java-try-catch-block\/\" \/>\n<meta property=\"og:site_name\" content=\"TechVidvan\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/TechVidvan\/\" \/>\n<meta property=\"article:published_time\" content=\"2023-10-20T13:30:19+00:00\" \/>\n<meta name=\"author\" content=\"TechVidvan Team\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@vidvantech\" \/>\n<meta name=\"twitter:site\" content=\"@vidvantech\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"TechVidvan Team\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"4 minutes\" \/>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Java Try Catch Block - TechVidvan","description":"In Java, try-catch block is used for exception handling. Allowing us to handle and manage runtime exceptions.","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:\/\/techvidvan.com\/tutorials\/java-try-catch-block\/","og_locale":"en_US","og_type":"article","og_title":"Java Try Catch Block - TechVidvan","og_description":"In Java, try-catch block is used for exception handling. Allowing us to handle and manage runtime exceptions.","og_url":"https:\/\/techvidvan.com\/tutorials\/java-try-catch-block\/","og_site_name":"TechVidvan","article_publisher":"https:\/\/www.facebook.com\/TechVidvan\/","article_published_time":"2023-10-20T13:30:19+00:00","author":"TechVidvan Team","twitter_card":"summary_large_image","twitter_creator":"@vidvantech","twitter_site":"@vidvantech","twitter_misc":{"Written by":"TechVidvan Team","Est. reading time":"4 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/techvidvan.com\/tutorials\/java-try-catch-block\/#article","isPartOf":{"@id":"https:\/\/techvidvan.com\/tutorials\/java-try-catch-block\/"},"author":{"name":"TechVidvan Team","@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/person\/e9c26e74dd3d87421f7ada9433b8cd22"},"headline":"Java Try Catch Block","datePublished":"2023-10-20T13:30:19+00:00","mainEntityOfPage":{"@id":"https:\/\/techvidvan.com\/tutorials\/java-try-catch-block\/"},"wordCount":681,"commentCount":0,"publisher":{"@id":"https:\/\/techvidvan.com\/tutorials\/#organization"},"image":{"@id":"https:\/\/techvidvan.com\/tutorials\/java-try-catch-block\/#primaryimage"},"thumbnailUrl":"","keywords":["java","java try catch block","try catch block","try catch block in java"],"articleSection":["Java Tutorials"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/techvidvan.com\/tutorials\/java-try-catch-block\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/techvidvan.com\/tutorials\/java-try-catch-block\/","url":"https:\/\/techvidvan.com\/tutorials\/java-try-catch-block\/","name":"Java Try Catch Block - TechVidvan","isPartOf":{"@id":"https:\/\/techvidvan.com\/tutorials\/#website"},"primaryImageOfPage":{"@id":"https:\/\/techvidvan.com\/tutorials\/java-try-catch-block\/#primaryimage"},"image":{"@id":"https:\/\/techvidvan.com\/tutorials\/java-try-catch-block\/#primaryimage"},"thumbnailUrl":"","datePublished":"2023-10-20T13:30:19+00:00","description":"In Java, try-catch block is used for exception handling. Allowing us to handle and manage runtime exceptions.","breadcrumb":{"@id":"https:\/\/techvidvan.com\/tutorials\/java-try-catch-block\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/techvidvan.com\/tutorials\/java-try-catch-block\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/techvidvan.com\/tutorials\/java-try-catch-block\/#primaryimage","url":"","contentUrl":""},{"@type":"BreadcrumbList","@id":"https:\/\/techvidvan.com\/tutorials\/java-try-catch-block\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/techvidvan.com\/tutorials\/"},{"@type":"ListItem","position":2,"name":"Java Try Catch Block"}]},{"@type":"WebSite","@id":"https:\/\/techvidvan.com\/tutorials\/#website","url":"https:\/\/techvidvan.com\/tutorials\/","name":"TechVidvan Blogs","description":"","publisher":{"@id":"https:\/\/techvidvan.com\/tutorials\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/techvidvan.com\/tutorials\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/techvidvan.com\/tutorials\/#organization","name":"TechVidvan","url":"https:\/\/techvidvan.com\/tutorials\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/logo\/image\/","url":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2024\/03\/techvidvan-logo-200x50-1.webp","contentUrl":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2024\/03\/techvidvan-logo-200x50-1.webp","width":200,"height":50,"caption":"TechVidvan"},"image":{"@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/www.facebook.com\/TechVidvan\/","https:\/\/x.com\/vidvantech"]},{"@type":"Person","@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/person\/e9c26e74dd3d87421f7ada9433b8cd22","name":"TechVidvan Team","description":"The TechVidvan Team delivers practical, beginner-friendly tutorials on programming, Java, Python, C++, DSA, AI, ML, data Science, Android, Flutter, MERN, Web Development, and technology. Our experts are here to help you upskill and excel in today\u2019s tech industry."}]}},"amp_enabled":true,"_links":{"self":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/posts\/88614","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/comments?post=88614"}],"version-history":[{"count":0,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/posts\/88614\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/"}],"wp:attachment":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/media?parent=88614"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/categories?post=88614"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/tags?post=88614"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}