{"id":88616,"date":"2023-11-06T18:00:23","date_gmt":"2023-11-06T12:30:23","guid":{"rendered":"https:\/\/techvidvan.com\/tutorials\/?p=88616"},"modified":"2023-11-06T18:00:23","modified_gmt":"2023-11-06T12:30:23","slug":"java-throw-keyword","status":"publish","type":"post","link":"https:\/\/techvidvan.com\/tutorials\/java-throw-keyword\/","title":{"rendered":"Java Throw Keyword"},"content":{"rendered":"<p>Exceptions in Java enable us to build high-quality code where faults are verified at compile time rather than run time and where we may define unique exceptions to facilitate code recovery and debugging.<\/p>\n<h2>Some of the scenarios have been given below,<\/h2>\n<h3>Purpose:<\/h3>\n<p>When a program is running, the throw keyword is used to consciously raise exceptions to signal extraordinary or incorrect circumstances.<\/p>\n<h3>Exception Creation:<\/h3>\n<p>To indicate unusual circumstances, throw creates an instance of an exception class and throws it.<\/p>\n<h3>Custom Exceptions:<\/h3>\n<p>By extending existing exception types, developers can construct their own unique exception classes that are tailored to the demands of particular applications.<\/p>\n<p><strong>Syntax:<\/strong><\/p>\n<p><strong>The syntax for using throw is:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">throw exceptionObject;,<\/pre>\n<p>Where exceptionObject is an instance of an exception class.<\/p>\n<h3>Exception Handling:<\/h3>\n<p>Thrown exceptions are caught and managed using try, catch, and finally, blocks, facilitating structured error handling.<\/p>\n<h3>Predefined Exceptions:<\/h3>\n<p>Each class in Java&#8217;s hierarchy of predefined exceptions represents a distinct kind of error or extraordinary circumstance.<\/p>\n<h3>Error Messages:<\/h3>\n<p>Developers can attach illustrative error messages with their exception throws to explain the reason for the uncommon circumstance.<\/p>\n<h3>Controlled Flow:<\/h3>\n<p>When exceptional circumstances arise, the throw keyword enables more controlled program flow.<\/p>\n<h3>Robustness:<\/h3>\n<p>By enabling methodical management of runtime problems, proper throw usage facilitates the construction of robust programming.<\/p>\n<p><strong>Example:<\/strong><\/p>\n<p>Throwing Unchecked Exception<\/p>\n<p><strong>Example code:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">class DivisionExample {\n        public static void main(String[] args) {\n            int dividend = 10;\n            int divisor = 0;\n            try {\n                int result = divide(dividend, divisor);\n                System.out.println(\"Result of division: \" + result);\n            } catch (ArithmeticException ex) {\n                System.out.println(\"Caught an arithmetic exception: \" + ex.getMessage());\n            }\n        }\n        public static int divide(int dividend, int divisor) {\n            if (divisor == 0) {\n                throw new ArithmeticException(\"Division by zero is not allowed.\");\n            }\n            return dividend \/ divisor;\n        }\n}<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<p><strong>Caught an arithmetic exception:<\/strong> Division by zero is not allowed.<\/p>\n<p><strong>Explanation:<\/strong><\/p>\n<ul>\n<li>In this example, we have a divide method that takes two integers as arguments and attempts to perform division. However, before performing the division, the method checks if the divisor is zero. If it is, the method throws an instance of the ArithmeticException class, which is an unchecked exception.<\/li>\n<li>In the main method, we call the divide method with a divisor of zero, intentionally triggering the ArithmeticException. We catch the exception using a try-catch block and print an error message.<\/li>\n<li>The unchecked exception ArithmeticException is commonly thrown when an arithmetic operation encounters an exceptional condition, such as division by zero in this case.<\/li>\n<\/ul>\n<p><strong>1. Program:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">class CustomException extends Exception {\n    public CustomException(String message) {\n        super(message);\n    }\n}\npublic class ThrowExample {\n    static void validateAge(int age) throws CustomException {\n        if (age &lt; 18) {\n            throw new CustomException(\"Person is not of legal age\");\n        } else {\n            System.out.println(\"Person is eligible\");\n        }\n    }\n   public static void main(String[] args) {\n        try {\n            int personAge = 15;\n            validateAge(personAge);\n        } catch (CustomException e) {\n            System.out.println(\"Caught exception: \" + e.getMessage());\n        }\n    }\n}<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<p><strong>Caught exception:<\/strong> Person is not of legal age<\/p>\n<p><strong>Explanation:<\/strong><\/p>\n<ul>\n<li>The code defines a custom exception class CustomException that extends the built-in Exception class.<\/li>\n<li>The validateAge method takes an int parameter age and throws a CustomException if the age is less than 18. If the age is 18 or older, it prints &#8220;Person is eligible&#8221;.<\/li>\n<li>In the main method, an int variable personAge is assigned a value of 15.<\/li>\n<li>The validateAge method is called with personAge as the argument. Since personAge is less than 18, the throw statement in the validateAge method is executed, throwing a CustomException.<\/li>\n<li>The thrown exception is caught by the catch block that specifies CustomException as the type of exception to catch. The caught exception is referred to as e.<\/li>\n<li>Inside the catch block, the error message of the caught exception (e.getMessage()) is retrieved and printed.<\/li>\n<\/ul>\n<p><strong>2. Program<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">class CustomException extends Exception {\n    public CustomException(String message) {\n        super(message);\n    }\n}\npublic class StudentAgeValidator {\n    static void validateAge(int age) throws CustomException {\n        if (age &lt; 0) {\n            throw new CustomException(\"Age cannot be negative\");\n        } else if (age &lt; 18) {\n            throw new CustomException(\"Student is underage\");\n        } else {\n            System.out.println(\"Student age is valid\");\n        }\n    }\n    public static void main(String[] args) {\n        try {\n            int studentAge = -5;\n            validateAge(studentAge);\n        } catch (CustomException e) {\n            System.out.println(\"Caught exception: \" + e.getMessage());\n        }\n    }\n}<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<p><strong>Caught exception:<\/strong> Age cannot be negative<\/p>\n<p><strong>Explanation:<\/strong><\/p>\n<ul>\n<li>The CustomException class is defined, which extends the built-in Exception class. It has a constructor to set the exception message.<\/li>\n<li>The StudentAgeValidator class contains a validateAge method that checks the validity of a student&#8217;s age. It throws the custom CustomException based on different conditions.<\/li>\n<li>In the main method, an int variable studentAge is assigned a value of -5.<\/li>\n<li>The validateAge method is called with studentAge as an argument. Since studentAge is negative, the first condition in the validateAge method is satisfied, leading to the throw statement being executed. This throws a CustomException with the message &#8220;Age cannot be negative&#8221;.<\/li>\n<li>The thrown exception is caught by the catch block that specifies CustomException as the type of exception to catch. The caught exception is referred to as e.<\/li>\n<li>Inside the catch block, the error message of the caught exception (e.getMessage()) is retrieved and printed.<\/li>\n<\/ul>\n<h3>Summary<\/h3>\n<p>The throw keyword in Java is a powerful tool for managing exceptions and error handling. It enables developers to intentionally trigger exceptions, creating a controlled way to respond to unexpected situations and ensure the reliability of their programs.<\/p>\n<h3>Difference between throw and throws:<\/h3>\n<table>\n<tbody>\n<tr>\n<td><b>Aspect<\/b><\/td>\n<td><b>throw<\/b><\/td>\n<td><b>throws<\/b><\/td>\n<\/tr>\n<tr>\n<td><b>\u00a0\u00a0<\/b><\/p>\n<p><b>\u00a0Usage<\/b><\/td>\n<td><span style=\"font-weight: 400\">Used inside a method to manually throw an exception.<\/span><\/td>\n<td><span style=\"font-weight: 400\">Used in method declarations to specify potential exceptions that might be thrown by the method.<\/span><\/td>\n<\/tr>\n<tr>\n<td><b>\u00a0<\/b><\/p>\n<p><b>\u00a0Syntax<\/b><\/td>\n<td><span style=\"font-weight: 400\">throw exceptionInstance;<\/span><\/td>\n<td><span style=\"font-weight: 400\">returnType methodName(parameters) throws ExceptionType1, ExceptionType2, &#8230;;<\/span><\/td>\n<\/tr>\n<tr>\n<td><b>\u00a0What It Does<\/b><\/td>\n<td><span style=\"font-weight: 400\">Signals are an exceptional condition within the method.<\/span><\/td>\n<td><span style=\"font-weight: 400\">Declares the exceptions that the method might propagate to its caller.<\/span><\/td>\n<\/tr>\n<tr>\n<td><b>\u00a0<\/b><b>Handling<\/b><\/td>\n<td><span style=\"font-weight: 400\">Requires the caller to catch or propagate the thrown exception.<\/span><\/td>\n<td><span style=\"font-weight: 400\">Informs the caller about the exceptions that need to be handled when calling the method.<\/span><\/td>\n<\/tr>\n<tr>\n<td><b>\u00a0<\/b><b>Exception Type<\/b><\/td>\n<td><span style=\"font-weight: 400\">Followed by an instance of an exception class or a subclass of<\/span> <span style=\"font-weight: 400\">Throwable<\/span><b>.<\/b><\/td>\n<td><span style=\"font-weight: 400\">Followed by a comma-separated list of exception classes.<\/span><\/td>\n<\/tr>\n<tr>\n<td><b>\u00a0Checked\/Unchecked<\/b><\/td>\n<td><span style=\"font-weight: 400\">It can be used to throw both checked and unchecked exceptions.<\/span><\/td>\n<td><span style=\"font-weight: 400\">Declares both checked and unchecked exceptions that might be thrown.<\/span><\/td>\n<\/tr>\n<tr>\n<td><b>\u00a0In Method Body<\/b><\/td>\n<td><span style=\"font-weight: 400\">Used inside a method&#8217;s body to explicitly throw an exception.<\/span><\/td>\n<td><span style=\"font-weight: 400\">Not used within the method body; only in the method&#8217;s declaration.<\/span><\/td>\n<\/tr>\n<tr>\n<td><b>\u00a0Mandatory<\/b><\/td>\n<td><span style=\"font-weight: 400\">It is not mandatory; it is used when the programmer wants to throw an exception.<\/span><\/td>\n<td><span style=\"font-weight: 400\">Not mandatory; used to indicate the potential exceptions the method might throw.<\/span><\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<h3>Throwing multiple exceptions in Java:<\/h3>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">public class MultipleExceptionsExample {\n    public static void main(String[] args) {\n        try {\n            processInput(-10);\n        } catch (IllegalArgumentException ex) {\n            System.out.println(\"Caught IllegalArgumentException: \" + ex.getMessage());\n        } catch (ArithmeticException ex) {\n            System.out.println(\"Caught ArithmeticException: \" + ex.getMessage());\n        }\n    }\n\n    public static void processInput(int value) throws IllegalArgumentException, ArithmeticException {\n        if (value &lt; 0) {\n            throw new IllegalArgumentException(\"Input value cannot be negative.\");\n        }\n        if (value == 0) {\n            throw new ArithmeticException(\"Input value cannot be zero.\");\n        }\n        System.out.println(\"Input value is valid.\");\n    }\n}<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<p><strong>Caught IllegalArgumentException:<\/strong> Input value cannot be negative.<\/p>\n<p><strong>Explanation:<\/strong><\/p>\n<ul>\n<li>In this example, the processInput method can throw both IllegalArgumentException and ArithmeticException. These exceptions are declared using the throws clause in the method signature.<\/li>\n<li>In the main method, we call the processInput method with different input values. If the input value is negative, an IllegalArgumentException is thrown, and if the input value is zero, an ArithmeticException is thrown. We use separate catch blocks to handle each type of exception and print appropriate messages.<\/li>\n<li>Remember that when you declare multiple exceptions in the throws clause, they are typically comma-separated. When calling the method that can throw these exceptions, you need to either handle them using separate catch blocks or declare that your calling method can also throw these exceptions using its own throws clause.<\/li>\n<\/ul>\n<h3>throw keyword Vs. try&#8230;catch&#8230;finally:<\/h3>\n<ul>\n<li>the throw keyword is used to manually throw exceptions<\/li>\n<li>try&#8230;catch&#8230;finally is used to handle exceptions within a specific code block, allowing for graceful recovery and cleanup tasks.<\/li>\n<\/ul>\n<h3>Conclusion<\/h3>\n<p>In the grand symphony of Java programming, the throw keyword is a pivotal note that resonates when disorder threatens the harmonious code. It hands developers the baton to conduct precise exception scenarios, sculpting graceful error handling and preserving the stability of applications. By grasping the significance and artistry of the throw keyword, Java programmers unlock a realm of controlled chaos that elevates software from mere functionality to true reliability.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Exceptions in Java enable us to build high-quality code where faults are verified at compile time rather than run time and where we may define unique exceptions to facilitate code recovery and debugging. Some&#46;&#46;&#46;<\/p>\n","protected":false},"author":1,"featured_media":88894,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[183],"tags":[296,5270,299,250,5271],"class_list":["post-88616","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-java","tag-java","tag-java-throw-keyword","tag-java-tutorial","tag-learn-java","tag-throw-keyword-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 Throw Keyword - TechVidvan<\/title>\n<meta name=\"description\" content=\"In Java programming, the throw keyword is a pivotal note that resonates when disorder threatens the harmonious code.\" \/>\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-throw-keyword\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Java Throw Keyword - TechVidvan\" \/>\n<meta property=\"og:description\" content=\"In Java programming, the throw keyword is a pivotal note that resonates when disorder threatens the harmonious code.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/techvidvan.com\/tutorials\/java-throw-keyword\/\" \/>\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-11-06T12:30:23+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=\"5 minutes\" \/>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Java Throw Keyword - TechVidvan","description":"In Java programming, the throw keyword is a pivotal note that resonates when disorder threatens the harmonious code.","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-throw-keyword\/","og_locale":"en_US","og_type":"article","og_title":"Java Throw Keyword - TechVidvan","og_description":"In Java programming, the throw keyword is a pivotal note that resonates when disorder threatens the harmonious code.","og_url":"https:\/\/techvidvan.com\/tutorials\/java-throw-keyword\/","og_site_name":"TechVidvan","article_publisher":"https:\/\/www.facebook.com\/TechVidvan\/","article_published_time":"2023-11-06T12:30:23+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":"5 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/techvidvan.com\/tutorials\/java-throw-keyword\/#article","isPartOf":{"@id":"https:\/\/techvidvan.com\/tutorials\/java-throw-keyword\/"},"author":{"name":"TechVidvan Team","@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/person\/e9c26e74dd3d87421f7ada9433b8cd22"},"headline":"Java Throw Keyword","datePublished":"2023-11-06T12:30:23+00:00","mainEntityOfPage":{"@id":"https:\/\/techvidvan.com\/tutorials\/java-throw-keyword\/"},"wordCount":1094,"commentCount":0,"publisher":{"@id":"https:\/\/techvidvan.com\/tutorials\/#organization"},"image":{"@id":"https:\/\/techvidvan.com\/tutorials\/java-throw-keyword\/#primaryimage"},"thumbnailUrl":"","keywords":["java","java throw keyword","Java Tutorial","Learn Java","throw keyword in java"],"articleSection":["Java Tutorials"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/techvidvan.com\/tutorials\/java-throw-keyword\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/techvidvan.com\/tutorials\/java-throw-keyword\/","url":"https:\/\/techvidvan.com\/tutorials\/java-throw-keyword\/","name":"Java Throw Keyword - TechVidvan","isPartOf":{"@id":"https:\/\/techvidvan.com\/tutorials\/#website"},"primaryImageOfPage":{"@id":"https:\/\/techvidvan.com\/tutorials\/java-throw-keyword\/#primaryimage"},"image":{"@id":"https:\/\/techvidvan.com\/tutorials\/java-throw-keyword\/#primaryimage"},"thumbnailUrl":"","datePublished":"2023-11-06T12:30:23+00:00","description":"In Java programming, the throw keyword is a pivotal note that resonates when disorder threatens the harmonious code.","breadcrumb":{"@id":"https:\/\/techvidvan.com\/tutorials\/java-throw-keyword\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/techvidvan.com\/tutorials\/java-throw-keyword\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/techvidvan.com\/tutorials\/java-throw-keyword\/#primaryimage","url":"","contentUrl":""},{"@type":"BreadcrumbList","@id":"https:\/\/techvidvan.com\/tutorials\/java-throw-keyword\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/techvidvan.com\/tutorials\/"},{"@type":"ListItem","position":2,"name":"Java Throw Keyword"}]},{"@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\/88616","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=88616"}],"version-history":[{"count":0,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/posts\/88616\/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=88616"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/categories?post=88616"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/tags?post=88616"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}