{"id":1247,"date":"2022-02-26T06:43:52","date_gmt":"2022-02-26T06:43:52","guid":{"rendered":"https:\/\/mdr.foobrdigital.com\/?p=1247"},"modified":"2022-02-26T06:43:52","modified_gmt":"2022-02-26T06:43:52","slug":"throw-and-throws","status":"publish","type":"post","link":"https:\/\/mudassirbackup.infinitycodestudio.com\/index.php\/2022\/02\/26\/throw-and-throws\/","title":{"rendered":"Throw and throws"},"content":{"rendered":"\n<p>In this tutorial, we will learn to use throw and throws keyword for exception handling with the help of examples.<\/p>\n\n\n\n<p id=\"introduction\">In Java, exceptions can be categorized into two types:<\/p>\n\n\n\n<ul><li><strong>Unchecked Exceptions:<\/strong>&nbsp;They are not checked at compile-time but at run-time.For example:&nbsp;<code>ArithmeticException<\/code>,&nbsp;<code>NullPointerException<\/code>,&nbsp;<code>ArrayIndexOutOfBoundsException<\/code>, exceptions under&nbsp;<code>Error<\/code>&nbsp;class, etc.<\/li><li><strong>Checked Exceptions:<\/strong>&nbsp;They are checked at compile-time. For example,&nbsp;<code>IOException<\/code>,&nbsp;<code>InterruptedException<\/code>, etc.<\/li><\/ul>\n\n\n\n<p>Refer to\u00a0Java Exceptions\u00a0to learn in detail about checked and unchecked exceptions.<\/p>\n\n\n\n<p>Usually, we don&#8217;t need to handle unchecked exceptions. It&#8217;s because unchecked exceptions occur due to programming errors. And, it is a good practice to correct them instead of handling them.<\/p>\n\n\n\n<p>This tutorial will now focus on how to handle checked exceptions using&nbsp;<code>throw<\/code>&nbsp;and&nbsp;<code>throws<\/code>.<\/p>\n\n\n\n<hr class=\"wp-block-separator\"\/>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"throws\">Java throws keyword<\/h2>\n\n\n\n<p>We use the&nbsp;<code>throws<\/code>&nbsp;keyword in the method declaration to declare the type of exceptions that might occur within it.<\/p>\n\n\n\n<p>Its syntax is:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>accessModifier returnType methodName() throws ExceptionType1, ExceptionType2 \u2026 {\n  \/\/ code\n}\n<\/code><\/pre>\n\n\n\n<p>As you can see from the above syntax, we can use&nbsp;<code>throws<\/code>&nbsp;to declare multiple exceptions.<\/p>\n\n\n\n<hr class=\"wp-block-separator\"\/>\n\n\n\n<h3 class=\"wp-block-heading\">Example 1: Java throws Keyword<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>import java.io.*;\nclass Main {\n  public static void findFile() throws IOException {\n    \/\/ code that may produce IOException\n    File newFile=new File(\"test.txt\");\n    FileInputStream stream=new FileInputStream(newFile);\n  }\n\n  public static void main(String&#91;] args) {\n    try{\n      findFile();\n    } catch(IOException e){\n      System.out.println(e);\n    }\n  }\n}\n<\/code><\/pre>\n\n\n\n<p><strong>Output<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><samp>java.io.FileNotFoundException: test.txt (No such file or directory)\n<\/samp><\/code><\/pre>\n\n\n\n<p>When we run this program, if the file&nbsp;<code>test.txt<\/code>&nbsp;does not exist,&nbsp;<code>FileInputStream<\/code>&nbsp;throws a&nbsp;<code>FileNotFoundException<\/code>&nbsp;which extends the&nbsp;<code>IOException<\/code>&nbsp;class.<\/p>\n\n\n\n<p>If a method does not handle exceptions, the type of exceptions that may occur within it must be specified in the&nbsp;<code>throws<\/code>&nbsp;clause so that methods further up in the call stack can handle them or specify them using&nbsp;<code>throws<\/code>&nbsp;keyword themselves.<\/p>\n\n\n\n<p>The&nbsp;<code>findFile()<\/code>&nbsp;method specifies that an&nbsp;<code>IOException<\/code>&nbsp;can be thrown. The&nbsp;<code>main()<\/code>&nbsp;method calls this method and handles the exception if it is thrown.<\/p>\n\n\n\n<hr class=\"wp-block-separator\"\/>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"multiple-exceptions\">Throwing multiple exceptions<\/h3>\n\n\n\n<p>Here&#8217;s how we can throw multiple exceptions using the&nbsp;<code>throws<\/code>&nbsp;keyword.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import java.io.*;\nclass Main {\n  public static void findFile() throws NullPointerException, IOException, InvalidClassException {\n    \n    \/\/ code that may produce NullPointerException\n    \u2026 \u2026 \u2026 \n\n    \/\/ code that may produce IOException\n    \u2026 \u2026 \u2026 \n\n    \/\/ code that may produce InvalidClassException \n    \u2026 \u2026 \u2026 \n  }\n\n  public static void main(String&#91;] args) {\n    try{\n      findFile();\n    } catch(IOException e1){\n      System.out.println(e1.getMessage());\n    } catch(InvalidClassException e2){\n      System.out.println(e2.getMessage());\n    }\n  }\n}\n<\/code><\/pre>\n\n\n\n<p>Here, the&nbsp;<code>findFile()<\/code>&nbsp;method specifies that it can throw&nbsp;<code>NullPointerException<\/code>,&nbsp;<code>IOException<\/code>, and&nbsp;<code>InvalidClassException<\/code>&nbsp;in its&nbsp;<code>throws<\/code>&nbsp;clause.<\/p>\n\n\n\n<p>Note that we have not handled the&nbsp;<code>NullPointerException<\/code>. This is because it is an unchecked exception. It is not necessary to specify it in the&nbsp;<code>throws<\/code>&nbsp;clause and handle it.<\/p>\n\n\n\n<hr class=\"wp-block-separator\"\/>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"versus-try-catch\">throws keyword Vs. try&#8230;catch&#8230;finally<\/h3>\n\n\n\n<p>There might be several methods that can cause exceptions. Writing&nbsp;<code>try...catch<\/code>&nbsp;for each method will be tedious and code becomes long and less-readable.<\/p>\n\n\n\n<p><code>throws<\/code>&nbsp;is also useful when you have checked exception (an exception that must be handled) that you don&#8217;t want to catch in your current method.<\/p>\n\n\n\n<hr class=\"wp-block-separator\"\/>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"throw\">Java throw keyword<\/h2>\n\n\n\n<p>The&nbsp;<code>throw<\/code>&nbsp;keyword is used to explicitly throw a single exception.<\/p>\n\n\n\n<p>When an exception is thrown, the flow of program execution transfers from the&nbsp;<code>try<\/code>&nbsp;block to the&nbsp;<code>catch<\/code>&nbsp;block. We use the&nbsp;<code>throw<\/code>&nbsp;keyword within a method.<\/p>\n\n\n\n<p>Its syntax is:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>throw throwableObject;<\/code><\/pre>\n\n\n\n<p>A throwable object is an instance of class&nbsp;<code>Throwable<\/code>&nbsp;or subclass of the&nbsp;<code>Throwable<\/code>&nbsp;class.<\/p>\n\n\n\n<hr class=\"wp-block-separator\"\/>\n\n\n\n<h3 class=\"wp-block-heading\">Example 2: Java throw keyword<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>class Main {\n  public static void divideByZero() {\n    throw new ArithmeticException(\"Trying to divide by 0\");\n  }\n\n  public static void main(String&#91;] args) {\n    divideByZero();\n  }\n}\n\n<\/code><\/pre>\n\n\n\n<p><strong>Output<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><samp>Exception in thread \"main\" java.lang.ArithmeticException: Trying to divide by 0\n    at Main.divideByZero(Main.java:3)\n    at Main.main(Main.java:7)\nexit status 1\n<\/samp><\/code><\/pre>\n\n\n\n<p>In this example, we are explicitly throwing an&nbsp;<code>ArithmeticException.<\/code><\/p>\n\n\n\n<p><strong>Note:<\/strong>&nbsp;<code>ArithmeticException<\/code>&nbsp;is an unchecked exception. It&#8217;s usually not necessary to handle unchecked exceptions.<\/p>\n\n\n\n<hr class=\"wp-block-separator\"\/>\n\n\n\n<h3 class=\"wp-block-heading\">Example 3: Throwing checked exception<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>import java.io.*;\nclass Main {\n  public static void findFile() throws IOException {\n    throw new IOException(\"File not found\");\n  }\n\n  public static void main(String&#91;] args) {\n    try {\n      findFile();\n      System.out.println(\"Rest of code in try block\");\n    } catch (IOException e) {\n      System.out.println(e.getMessage());\n    }\n  }\n}\n<\/code><\/pre>\n\n\n\n<p><strong>Output<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><samp>File not found\n<\/samp><\/code><\/pre>\n\n\n\n<p>The&nbsp;<code>findFile()<\/code>&nbsp;method throws an&nbsp;<code>IOException<\/code>&nbsp;with the message we passed to its constructor.<\/p>\n\n\n\n<p>Note that since it is a checked exception, we must specify it in the&nbsp;<code>throws<\/code>&nbsp;clause.<\/p>\n\n\n\n<p>The methods that call this&nbsp;<code>findFile()<\/code>&nbsp;method need to either handle this exception or specify it using&nbsp;<code>throws<\/code>&nbsp;keyword themselves.<\/p>\n\n\n\n<p>We have handled this exception in the&nbsp;<code>main<\/code><code>()<\/code>&nbsp;method. The flow of program execution transfers from the&nbsp;<code>try<\/code>&nbsp;block to&nbsp;<code>catch<\/code>&nbsp;block when an exception is thrown. So, the rest of the code in the&nbsp;<code>try<\/code>&nbsp;block is skipped and statements in the&nbsp;<code>catch<\/code>&nbsp;block are executed.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>In this tutorial, we will learn to use throw and throws keyword for exception handling with the help of examples. In Java, exceptions can be categorized into two types: Unchecked Exceptions:&nbsp;They are not checked at compile-time but at run-time.For example:&nbsp;ArithmeticException,&nbsp;NullPointerException,&nbsp;ArrayIndexOutOfBoundsException, exceptions under&nbsp;Error&nbsp;class, etc. Checked Exceptions:&nbsp;They are checked at compile-time. For example,&nbsp;IOException,&nbsp;InterruptedException, etc. Refer to\u00a0Java Exceptions\u00a0to [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[569],"tags":[],"_links":{"self":[{"href":"https:\/\/mudassirbackup.infinitycodestudio.com\/index.php\/wp-json\/wp\/v2\/posts\/1247"}],"collection":[{"href":"https:\/\/mudassirbackup.infinitycodestudio.com\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/mudassirbackup.infinitycodestudio.com\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/mudassirbackup.infinitycodestudio.com\/index.php\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/mudassirbackup.infinitycodestudio.com\/index.php\/wp-json\/wp\/v2\/comments?post=1247"}],"version-history":[{"count":0,"href":"https:\/\/mudassirbackup.infinitycodestudio.com\/index.php\/wp-json\/wp\/v2\/posts\/1247\/revisions"}],"wp:attachment":[{"href":"https:\/\/mudassirbackup.infinitycodestudio.com\/index.php\/wp-json\/wp\/v2\/media?parent=1247"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/mudassirbackup.infinitycodestudio.com\/index.php\/wp-json\/wp\/v2\/categories?post=1247"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/mudassirbackup.infinitycodestudio.com\/index.php\/wp-json\/wp\/v2\/tags?post=1247"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}