Java - Difference Between Throw and Throws Keywords

Here, we will learn about throw and throws and what are the core concepts of throw and throws and what are the differences between throw and throws, Compare throw and throws. By Preeti Jain and Shahnail Khan Last updated : March 25, 2024

Exception handling is a crucial aspect of Java programming, and understanding the distinction between 'throw' and 'throws' is essential. 'throw' is used to manually throw exceptions within code blocks, while 'throws' is used in method signatures to declare exceptions that the method might generate. In this article, we'll cover the differences between these two in detail with relevant examples.

What is the 'throw' keyword in Java?

In Java, 'throw' is a keyword used to explicitly throw an exception within a method or a block of code. It is typically followed by an instance of an exception class or a subclass thereof, which means that the exception is represented by a class in Java, and it can be a specific class designed for that issue.

  • throw is a keyword introduced in java for exception handling.
  • Sometimes we can create exception object explicitly and we can handover to the jvm manually for these we have to use throw keyword.
  • Purpose of throw keyword is to handover our created exception objects to the jvm manually.

Example 1: With using throw keyword

class ThrowExample {
  public static void main(String[] args) {
    System.out.println(10 / 0);
    throw new ArithmeticException("/ by zero");
  }
}

Output

D:\Java Articles>java ThrowExample
Exception in thread "main" java.lang.ArithmeticException: / by zero
        at ThrowExample.main(ThrowExample.java:6)

Example 2: Without using throw keyword

class ThrowExample {
  public static void main(String[] args) {
    System.out.println(10 / 0);
  }
}

Output

D:\Java Articles>java WithoutThrow
Exception in thread "main" java.lang.ArithmeticException: / by zero
        at WithoutThrow.main(WithoutThrow.java:6)

Explanation

  • In Example 1, Developer is responsible to create exception object explicitly and handover object to the jvm manually (i.e. here main method is not responsible to create object and handover to jvm internally). We will get the same output in both ways and the methodologies are different.
  • In Example 2, main() method is responsible to create exception object explicitly and handover object to the jvm internally (i.e. here, programmer is not responsible to create object and handover to jvm manually). We will get the same output in both ways and the methodology are different.
  • throw keyword is used to throw an exception from any method or static block in java.
  • Best use of throw keyword is for user defined or customized exception.
  • throw keyword is applicable only for Throwable objects.

Example 3: With using throw keyword

public void checkAge(int age) {
  if (age < 0) {
    throw new IllegalArgumentException("Age cannot be negative");
  }
}

Explanation

  • In this example, we have a method named 'checkAge' that takes an 'age' as input.
  • Inside the method, we check if the 'age' is less than 0, which would be invalid.
  • If it's negative, we use 'throw' to create and throw a new instance of the 'IllegalArgumentException' class.
  • The message "Age cannot be negative" is passed to the constructor of 'IllegalArgumentException' to provide information about the problem.

What is the 'throws' keyword in Java?

In Java, the 'throws' keyword is used in the method signature to declare that a particular method might throw one or more types of exceptions.

  • throws is a keyword introduced in java for exception handling.
  • In our program, if there is a possibilities of raising checked exception then compulsory we should handle the checked exception otherwise we will get compile time error (ie. unreported exception xxx(exception name in place xxx) must be caught or declared to be thrown).

Example 1: Without using 'throws' keyword

import java.io.*;
class ThrowsExample {
  public static void main(String[] args) {
    PrintWriter pw = new PrintWriter("java.txt");
    pw.println("welcome in java world");
  }
}

Output

D:\Java Articles>javac ThrowsExample.java
ThrowsExample.java:6: error: unreported exception FileNotFoundException; must be
 caught or declared to be thrown
        PrintWriter pw = new PrintWriter("java.txt");
                         ^
1 error

We can use throws keyword to delegate the responsibility to the caller method (i.e. it may be another method or jvm) then caller method is responsible to handle that exception.

Example 2: With using 'throws' keyword

class ThrowsExample2 {
  public static void main(String[] args) throws InterruptedException {
    Thread.sleep(1000);
  }
}

Explanation

  • throws keyword is applicable only for checked exceptions otherwise we will get compile time error (ie. unreported exception).
  • Usage of throws keyword for unchecked exception is meaningless you can use if you want but no compile time error we will get (no impact on unchecked exception).
  • throws keyword does not prevent abnormal termination of the program.

Example 3: With using 'throws' keyword

import java.io.FileNotFoundException;
import java.io.FileReader;

public void readFile() throws FileNotFoundException {
  FileReader file = new FileReader("xyz.txt");
  // code to read from file
}

Explanation

  • Here, we have a method named 'readFile' which is supposed to read from a file named 'xyz.txt'.
  • We use 'throws' in the method signature to declare that this method might throw a 'FileNotFoundException'.
  • Inside the method, we create a 'FileReader' object for the 'xyz.txt' file.
  • By declaring 'throws FileNotFoundException', we inform the caller that they need to handle this exception when using the 'readFile' method, either by catching it or declaring it in their method signature.

Difference Between Throw and Throws Keywords in Java

The following are the differences between throw and throws keywords in Java:

Sr. No throw Keyword throws Keyword
1. 'throw' is used inside a method or a block to manually throw an exception. 'throws' is used in the method signature to declare the exceptions that a method might throw.
2. 'throw' is followed by an instance of an exception class or a subclass. 'throws' is followed by the names of exception classes separated by commas.
3. 'throw' is used to explicitly raise an exception during program execution. 'throws' is used to declare the exceptions that a method might throw, leaving it to the caller to handle them.
4. The responsibility of handling the exception is with the method where 'throw' is used. The responsibility of handling the exception is typically shifted to the caller method or to higher-level exception handlers.
5. 'throw' provides finer control over exception handling within the method or block of code. 'throws' provides broader information to the caller about potential exceptions that might occur during the method's execution.
6. 'throw' is not mandatory in method signatures. 'throws' is optional but recommended in method signatures if the method can throw checked exceptions.
7. 'throw' can be used to throw both checked and unchecked exceptions. 'throws' is used only for declaring checked exceptions that a method might throw.
8. 'throw' can be used to throw only one exception at a time. 'throws' can declare multiple exceptions separated by commas.
9. 'throw' is executed when a specific condition is met within the method. 'throws' is part of the method signature and doesn't directly affect the execution flow of the method.


Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.