{"id":88620,"date":"2023-11-08T18:00:46","date_gmt":"2023-11-08T12:30:46","guid":{"rendered":"https:\/\/techvidvan.com\/tutorials\/?p=88620"},"modified":"2023-11-08T18:00:46","modified_gmt":"2023-11-08T12:30:46","slug":"java-throw-and-throws","status":"publish","type":"post","link":"https:\/\/techvidvan.com\/tutorials\/java-throw-and-throws\/","title":{"rendered":"Difference Between throw and throws in Java"},"content":{"rendered":"<p>The words &#8220;throw&#8221; and &#8220;throws&#8221; in Java are used by programmers to describe potential problems that might appear unexpectedly while a program is running. The method for overcoming these problems is exception handling. They are used in many different situations and computer languages, and they have a variety of functions.<\/p>\n<h2>&#8220;throw&#8221;:<\/h2>\n<p>The keyword &#8220;throw&#8221; is frequently used in programming languages to explicitly raise or cause an exception. If an extraordinary event or error occurs while a program is being executed, you can use &#8220;throw&#8221; to expressly generate an exception, signalling that something unexpected has happened. This approach is typically taken when a programmer runs into a problem that requires stopping the program&#8217;s normal flow. The program&#8217;s control flow is then transferred to the closest applicable exception-handling code after &#8220;throw&#8221; has been used.<\/p>\n<h3>&#8220;throws&#8221;:<\/h3>\n<p>In function and method declarations, the word &#8220;throws&#8221; denotes the possibility that the code will throw one or more different exception types when called. It serves as a means of informing callers of the function or method that they must propagate or handle such exceptions. The developer indicates that the caller must take into account the possibility of exceptions being thrown by that function or method by stating &#8220;throws&#8221; in the function signature.<\/p>\n<h4>Prerequisite:<\/h4>\n<p>&#8220;Throw&#8221; and &#8220;throws&#8221; are integral aspects of exception handling in Java. The &#8220;throw&#8221; keyword facilitates the deliberate throwing of exceptions within a specific method or code block. On the other hand, the &#8220;throws&#8221; keyword finds its place in method signatures. It indicates that a method might potentially give rise to certain exceptions during its execution. In essence, &#8220;throw&#8221; is employed to explicitly generate exceptions, while &#8220;throws&#8221; is included in method declarations to highlight the possibility of exceptions being generated.<\/p>\n<h3>Difference between throw and throws Keyword in Java:<\/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 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\">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\">Not mandatory; 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<p><strong>Example Program:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">import java.io.IOException;\n\npublic class ExceptionExample {\n    public static void main(String[] args) {\n        try {\n            int result = divide(10, 0);\n            System.out.println(\"Result: \" + result);\n        } catch (ArithmeticException e) {\n            System.out.println(\"An arithmetic exception occurred: \" + e.getMessage());\n        }\n    }\n\n    public static int divide(int numerator, int denominator) throws ArithmeticException {\n        if (denominator == 0) {\n            throw new ArithmeticException(\"Division by zero!\");\n        }\n        return numerator \/ denominator;\n    }\n}<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<p><strong>An arithmetic exception occurred:<\/strong> Division by zero!<\/p>\n<p><strong>Explanation:<\/strong><\/p>\n<p><strong>Import Statement:<\/strong> import java.io.IOException; is the first import statement in the code. The IOException import is not being used in this code sample, thus it may be removed without having any negative effects on how the program behaves.<\/p>\n<p>ExceptionExample is a class that has been declared. The main method, which is the program&#8217;s entry point, is contained in this class.<\/p>\n<p><strong>Main Method:<\/strong> The main method is where the execution of the program begins. The division function is called inside the try block with the inputs 10 and 0. An error will be raised because this function call tries to divide 10 by 0.<\/p>\n<p>A try-catch block is used in the programming to manage exceptions. Due to the attempt to divide by zero, when the divide function is called, it throws an ArithmeticException. The catch block that follows catches this exception.<\/p>\n<p><strong>Catch Block:<\/strong> Using e.getMessage(), the catch block publishes an error message after catching the ArithmeticException. This error message denotes a division by zero miscalculation.<\/p>\n<p><strong>Method:<\/strong> divide The divide method is a public static int divide(int numerator, int denominator) that raises an ArithmeticException. Numerator and denominator, two integer parameters, are required for this procedure. This method may throw an ArithmeticException, as indicated by the throws ArithmeticException phrase in the method signature.<\/p>\n<p><strong>Division Check:<\/strong> The condition if (denominator == 0) is used within the divide method to check for division by zero. A new ArithmeticException is thrown with the message &#8220;Division by zero!&#8221; if the denominator is 0.<\/p>\n<p><strong>Throw Statement:<\/strong> When a division by zero circumstance arises, the throw statement generates and throws an exception. The normal program flow is interrupted, and control is then passed to the closest suitable catch block.<\/p>\n<p><strong>Returning Result:<\/strong> The divide method computes the outcome by dividing the numerator by the denominator and then returns the outcome if the division is legitimate (the denominator is not zero).<\/p>\n<h4>Program 1:<\/h4>\n<h4>Using \u201cthrow\u201d to Custom Exception:<\/h4>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">class CustomException extends Exception {\n    public CustomException(String message) {\n        super(message);\n    }\n}\n\npublic class ThrowCustomExceptionExample {\n    public static void main(String[] args) {\n        try {\n            validateAge(15);\n        } catch (CustomException e) {\n            System.out.println(\"Custom Exception caught: \" + e.getMessage());\n        }\n    }\n\n    public static void validateAge(int age) throws CustomException {\n        if (age &lt; 18) {\n            throw new CustomException(\"You must be at least 18 years old.\");\n        }\n        System.out.println(\"Age is valid.\");\n    }\n}<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<p><strong>Custom Exception caught:<\/strong> You must be at least 18 years old.<\/p>\n<p><strong>Explanation:<\/strong><\/p>\n<p>The CustomException exception type is created by this software by extending the Exception class. The validateAge function throws this specific exception if the user is under the legal drinking age of 18. Due to the age being under 18, the main method calls validateAge(15), which raises the particular exception. Both the exception&#8217;s capture and the error message are written in the main method&#8217;s try-catch block.<\/p>\n<h4>Program 2:<\/h4>\n<h4>Using \u201cthrows\u201d in Method Signature:<\/h4>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">import java.io.FileNotFoundException;\nimport java.io.FileReader;\nimport java.io.IOException;\n\npublic class ThrowsExample {\n    public static void main(String[] args) {\n        try {\n            readFromFile(\"example.txt\");\n        } catch (FileNotFoundException e) {\n            System.out.println(\"File not found: \" + e.getMessage());\n        } catch (IOException e) {\n            System.out.println(\"IO Exception: \" + e.getMessage());\n        }\n    }\n\n    public static void readFromFile(String filename) throws FileNotFoundException, IOException {\n        FileReader reader = new FileReader(filename);\n        int character;\n        while ((character = reader.read()) != -1) {\n            System.out.print((char) character);\n        }\n        reader.close();\n    }\n}<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<p><strong>File not found:<\/strong> example.txt (The file &#8220;example.txt&#8221; does not exist in this context)<\/p>\n<p><strong>Explanation:<\/strong><\/p>\n<p>This application&#8217;s readFromFile function uses the filename parameter to attempt to read characters from a file. Because throwing exceptions is allowed in both the constructor for the FileReader and the read method, the throws clause in the method signature also includes the exceptions FileNotFoundException and IOException.<\/p>\n<p>The readFromFile function is called by the main method with the argument &#8220;example.txt,&#8221; even though there isn&#8217;t a file with that name in this case. A FileNotFoundException is raised as a result, and the catch block prints the relevant error message.<\/p>\n<h3>Throws keyword Vs. try&#8230;catch&#8230;finally:<\/h3>\n<ul>\n<li>The &#8220;throws&#8221; keyword is used at the method declaration level to indicate which exceptions might be propagated to the caller.<\/li>\n<li>The &#8220;try&#8230;catch&#8230;finally&#8221; construct is used within a specific code block to handle exceptions that might occur during the execution of that block.<\/li>\n<\/ul>\n<h3>Summary:<\/h3>\n<p>While &#8220;throws&#8221; is used to indicate that a function or method may throw a certain exception in its declaration, &#8220;throw&#8221; is used to manually raise exceptions. For effective programming exception handling, both are necessary.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>The words &#8220;throw&#8221; and &#8220;throws&#8221; in Java are used by programmers to describe potential problems that might appear unexpectedly while a program is running. The method for overcoming these problems is exception handling. They&#46;&#46;&#46;<\/p>\n","protected":false},"author":1,"featured_media":88904,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[183],"tags":[5272,5273,5274,5275,5276,299],"class_list":["post-88620","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-java","tag-difference-between-throw-and-throws","tag-java-throw","tag-java-throw-and-throws","tag-java-throw-vs-throws","tag-java-throws","tag-java-tutorial"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v27.7 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\n<title>Difference Between throw and throws in Java - TechVidvan<\/title>\n<meta name=\"description\" content=\"Java Throw vs Throws are integral aspects of exception handling in Java. For effective programming exception handling, both are necessary.\" \/>\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-and-throws\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Difference Between throw and throws in Java - TechVidvan\" \/>\n<meta property=\"og:description\" content=\"Java Throw vs Throws are integral aspects of exception handling in Java. For effective programming exception handling, both are necessary.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/techvidvan.com\/tutorials\/java-throw-and-throws\/\" \/>\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-08T12:30:46+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":"Difference Between throw and throws in Java - TechVidvan","description":"Java Throw vs Throws are integral aspects of exception handling in Java. For effective programming exception handling, both are necessary.","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-and-throws\/","og_locale":"en_US","og_type":"article","og_title":"Difference Between throw and throws in Java - TechVidvan","og_description":"Java Throw vs Throws are integral aspects of exception handling in Java. For effective programming exception handling, both are necessary.","og_url":"https:\/\/techvidvan.com\/tutorials\/java-throw-and-throws\/","og_site_name":"TechVidvan","article_publisher":"https:\/\/www.facebook.com\/TechVidvan\/","article_published_time":"2023-11-08T12:30:46+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-and-throws\/#article","isPartOf":{"@id":"https:\/\/techvidvan.com\/tutorials\/java-throw-and-throws\/"},"author":{"name":"TechVidvan Team","@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/person\/e9c26e74dd3d87421f7ada9433b8cd22"},"headline":"Difference Between throw and throws in Java","datePublished":"2023-11-08T12:30:46+00:00","mainEntityOfPage":{"@id":"https:\/\/techvidvan.com\/tutorials\/java-throw-and-throws\/"},"wordCount":1082,"commentCount":0,"publisher":{"@id":"https:\/\/techvidvan.com\/tutorials\/#organization"},"image":{"@id":"https:\/\/techvidvan.com\/tutorials\/java-throw-and-throws\/#primaryimage"},"thumbnailUrl":"","keywords":["difference between throw and throws","java throw","java throw and throws","java throw vs throws","java throws","Java Tutorial"],"articleSection":["Java Tutorials"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/techvidvan.com\/tutorials\/java-throw-and-throws\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/techvidvan.com\/tutorials\/java-throw-and-throws\/","url":"https:\/\/techvidvan.com\/tutorials\/java-throw-and-throws\/","name":"Difference Between throw and throws in Java - TechVidvan","isPartOf":{"@id":"https:\/\/techvidvan.com\/tutorials\/#website"},"primaryImageOfPage":{"@id":"https:\/\/techvidvan.com\/tutorials\/java-throw-and-throws\/#primaryimage"},"image":{"@id":"https:\/\/techvidvan.com\/tutorials\/java-throw-and-throws\/#primaryimage"},"thumbnailUrl":"","datePublished":"2023-11-08T12:30:46+00:00","description":"Java Throw vs Throws are integral aspects of exception handling in Java. For effective programming exception handling, both are necessary.","breadcrumb":{"@id":"https:\/\/techvidvan.com\/tutorials\/java-throw-and-throws\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/techvidvan.com\/tutorials\/java-throw-and-throws\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/techvidvan.com\/tutorials\/java-throw-and-throws\/#primaryimage","url":"","contentUrl":""},{"@type":"BreadcrumbList","@id":"https:\/\/techvidvan.com\/tutorials\/java-throw-and-throws\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/techvidvan.com\/tutorials\/"},{"@type":"ListItem","position":2,"name":"Difference Between throw and throws in Java"}]},{"@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\/88620","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=88620"}],"version-history":[{"count":0,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/posts\/88620\/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=88620"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/categories?post=88620"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/tags?post=88620"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}