Java throws Keyword

The Java throws keyword is used for handling checked exceptions. We know that Checked exceptions (compile-time) force us to handle them. If we don’t handle them, then the program will not compile.

There are two ways for handling checked exceptions, either by writing a try-catch block or using the keyword throws.

What is a throws Keyword in Java?

The Java throws keyword is used to declare an exception. It gives information to the programmer that there may occur an exception, so it is better for the programmer to provide the exception handling code so that normal flow can be maintained.

The main advantage of using the throws keyword is that Checked Exceptions can be propagated (forwarded in the call stack).

Syntax of the Java throws keyword:

 void methodName() throws Exception


Handling Exceptions using the throws keyword – examples

Have a look at this code:

class Test {

  public static void main(String[] args) {
  }

  private void validateStatus(String status) {
    if (status.equals("invalid")) {
      throw new IOException("Status of the file is invalid, the stream is closed!");
    }
  }
}


Here in the validateStatus method, we explicitly throw a checked exception, and therefore we are forced to handle it, either with a try-catch block or using a throws keyword.

Let’s see what happens when we use the try-catch block:

class Test {

  public static void main(String[] args) {
    Test test = new Test();
    test.validateStatus("valid"); // OK
    test.validateStatus("invalid"); // this will cause an exception
    }

  private void validateStatus(String status) {
    if (status.equals("invalid")) {
      try {
        throw new IOException("Status of the file is invalid, the stream is closed!");
      } catch (IOException e) {
        System.out.println("Exception occurred with message: " + e.getMessage());
      }
    } else {
      System.out.println("Status in valid.");
    }
  }
}
Output: Status in valid. Exception occurred with message: Status of the file is invalid, the stream is closed!
 
Using a try-catch block, we got the desired result. The first call of the validateStatus method passed without an error, and the second caused an exception, but since we handled it, we got our error message in the output.

See now how we can handle it using keyword throws:

class Test {

  public static void main(String[] args) {
    Test test = new Test();
    test.validateStatus("valid");
    test.validateStatus("invalid");
  }

  private 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.");
    }
  }
}


Now, we have added the keyword throws right next to the method signature, and thus we have handled it,  but only at that spot. We still have to handle it at the spot from where we call the method since it has the throws keyword in its declaration. We need to either catch that error with the try-catch block or propagate it further in the call chain with the throws keyword.

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.

Since the main method is the first method in the chain, if we put the throws keyword, there is no other method that will be able to handle the exception on its side, and so we get an exception as if we didn’t even handle it.

This example shows that:

class Test {

  public static void main(String[] args) throws IOException {
    Test test = new Test();
    test.validateStatus("valid");
    test.validateStatus("invalid");
  }

  private 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.");
    }
  }
}
Output: Status in valid. Exception in thread “main” java.io.IOException: Status of the file is invalid, the stream is closed! at com.company.Test.validateStatus(User.java:20) at com.company.Test.main(User.java:13)
 
But, since we are aware that the main method is the starting point of any Java program, we will handle the exception using the try-catch block:
 
class Test {

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

    try {
      test.validateStatus("valid");
      test.validateStatus("invalid");
    } catch (IOException e) {
      System.out.println("Exception occurred with message: " + e.getMessage());
    }
  }

  private 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.");
    }
  }
}
Output: Status in valid. Exception occurred with message: Status of the file is invalid, the stream is closed!
 
You can see that this time we did not get an exception in the output, but only our message, which means that we handled it properly and that the program did not stop when the exception occurred.
 
That’s it!

Leave a Reply

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