Difference Between throw and throws in Java

This tutorial will discuss the difference between throw and throws keywords.

Java throw Keyword

We use the keyword throw when we want to explicitly throw an exception.

 throw new Exception();

Example of using the throw keyword in Java:

class Test {

  public static void main(String[] args) {
    Test test = new Test();
    test.reserveSeats(8);
  }

  private void reserveSeats(int numberOfSeats) {
    if (numberOfSeats > 5) {
      throw new IllegalArgumentException("No more than 5 seats can be reserved.");
    } else {
      System.out.println("Reservation successful!");
    }
  }
}
Output: Exception in thread “main” java.lang.IllegalArgumentException: No more than 5 seats can be reserved at com.company.Test.reserveSeats(User.java:18) at com.company.Test.main(User.java:11)

Here in the reserveSeats method, we wrote the code that throws an exception in case the user tries to reserve more than 5 seats per reservation.

Java throws keyword

The throws clause is used to declare an exception.

The syntax of the throws keyword:

 void methodName() throws Exception


Example of using the throws keyword in Java:

class Test {

  public void validateStatus(String status) throws IOException {
    if (status.equals("invalid")) {
      throw new IOException("Status of the file is invalid, the stream is closed!");
    } else {
      System.out.println("Status in valid.");
    }
  }
}

Here in the validateStatus method we explicitly throw an exception in case the status of the file is invalid.

Since IOException is a checked exception, we must handle it either with a try-catch block, or a throws keyword. In this case, we put the throws keyword in the method declaration, and we handled the exception.

There is a rule in Java that says: If you are calling a method that declares an exception, you must either catch or declare the exception.


throws
vs throw in Java

                                        throw                                      throws
  Java throw keyword is used to explicitly throw an exception. Java throws keyword is used to declare an exception.
  A checked exception cannot be propagated using throw only. A checked exception can be propagated with throws.
  The throw keyword is followed by an instance. the throws keyword is followed by class.
  The throw keyword is used within the method. The throws keyword is used with the method signature.
     


That’s it!

Leave a Reply

Your email address will not be published. Required fields are marked *