throw and throws keywords in Java

throw and throws keywords in Java

In this article, I am going to discuss throw and throws keywords in Java with Examples. Please read our previous article where we discussed Finally block in Java with Examples. At the end of this article, you will understand the following pointers in detail.

  1. throw keyword in Java
  2. throws keyword in Java
  3. What is the need of having throws keyword when you can handle exception using try-catch?
  4. Difference Between Throw and Throws keywords in java
throw keyword in Java

By default, all predefined exceptions are created and thrown implicitly and identified by JVM. But if we want to throw the exceptions explicitly then we have to use throw keyword.

Syntax: throw exception;

The “throw” keyword is used to throw an exception manually. In most of cases, we use it for throwing checked exceptions explicitly. The “throw” keyword must follow the Throwable type of object and It must be used in method logic. Since it is a transfer statement, we cannot place a statement after the throw keyword. It leads to a compile-time error “Unreachable statement”.

For example:

throw keyword in Java

ArithmeticException is a runtime exception so the compiler does not check its Exception Handling.

throw and throws keywords in Java

InterruptedException is a direct subclass of Exception class that means it a checked exception. So we must catch or report this exception using throws keyword. As we have not done either of both compiler throws CE: “Unreported exception InterruptedException must be caught or declared to be thrown”.

Below code shows correct syntax for throwing a checked exception

using throw keyword in Java

Sample Program for Java Throw Keyword
public class Main
{
  static void validate (int age)
  {
    if (age < 18)
      throw new ArithmeticException ("not valid");
    else
      System.out.println ("welcome to vote");
  }
  public static void main (String args[])
  {
    validate (13);
    System.out.println ("rest of the code...");
  }
}

Output:

Program for Java Throw Keyword

throws keyword in Java

The “throws” keyword is used to report that raised exception to the caller. It is mandatory for checked exceptions for reporting if they are not handled.

This keyword is used to transfer the responsibility of Exception handling to its caller method. The “throws” keyword is used to declare exceptions. It doesn’t throw an exception. It specifies that there may occur an exception in the method. It is always used with a method signature.

Syntax:

throws keywords in Java

What is the need of having throws keyword when you can handle exception using try-catch?

Suppose you have several such methods that can cause exceptions, in that case, it would be tedious to write this try-catch for each method. The code will become unnecessarily long and will be less readable.

One way to overcome this problem is by using throws like this: declare the exceptions in the method signature using throws and handle the exceptions where you are calling this method by using try-catch.

Another advantage of using this approach is that you will be forced to handle the exception when you call this method, all the exceptions that are declared using throws, must be handled where you are calling this method else you will get a compilation error.

Examples to understand java throws keyword:

The “throws” keyword must throw a Throwable type of class name. It must be used in method prototype after method parenthesis.

Examples to understand java throws keyword

We are not allowed to write a catch block with checked exception without throwing it from the try block. It leads to CE: “exception never thrown from the corresponding try statement”.

In below program catch block leads to the above exception

What is the need of having throws keyword when you can handle exception using try-catch?

Below program compiles fine

Difference Between Throw and Throws keywords in java

We can catch and also report using throws

catch and also report using throws in java

Sample Program using throws Keyword in Java
import java.io.IOException;  
public class Main
{
  void m() throws IOException
  {
    throw new IOException ("device error");	//checked exception  
  }
  void n() throws IOException
  {
    m();
  }
  void p()
  {
    try
    {
      n();
    } catch (Exception e)
    {
      System.out.println ("exception handled");
    }
  }
  public static void main (String args[])
  {
    Main obj = new Main();
    obj.p ();
    System.out.println ("normal flow...");
  }
}

Output:

Program using throws Keyword in Java

Note: It is always recommended to use try-catch-finally blocks to handle the exceptions. But it is not recommended to transfer the exception handling job to its caller method by using throws keyword which always leads to abnormal termination.

Difference Between Throw and Throws keywords in java

The “throws” clause is used when the programmer does not want to handle the exception and throw it out of a method whereas the “throw” clause is used when the programmer wants to throw an exception explicitly and wants to handle it using catch block. Hence throws and throw are contradictory.

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 using throws
The throw is followed by an instance Throws is followed by a class
The throw is used within the method Throws is used with the method signature
You cannot throw multiple exceptions Using throws you can declare multiple exceptions

In the next article, I am going to discuss How to Create a Custom Exception in Java with Examples. I hope you enjoy this article. I would like to have your feedback. Please post your feedback, question, or comments about this article.

Leave a Reply

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