Difference between throw and throws in java

We have learned about the throw and throws in java. Both have different purposes and both are used in different scenarios. Here we will find what is the difference between throw and throws in java.

Difference between throw and throws in java

1. throws keyword is used to declare an exception with the method name. It works like the try-catch block because the caller needs to handle the exception thrown by throws. On the other hand, the throw keyword is used to throw an exception explicitly.

2. throw is followed by an instance of Exception class and throws is followed by exception class names. It means throw keyword always use the object of exception class where the throws keyword uses the exception class.

throw

throw new ArithmeticException("Arithmetic Exception");

throws

throws ArithmeticException;

3. throw keyword is used within the body of a method, On the other hand throws is used in method signature to declare the exceptions.

throw:

void usingThrowKeyword()
{
   try 
   {
      //throwing arithmetic exception using throw
      throw new ArithmeticException("You can’t divide a number by zero.");
   }
   catch (ArithmeticException e)
   {
      // handling exception
   }
}

throws:

//arithmetic exception using throws
void usingThrowsKeyword() throws ArithmeticException
{
   //Statements
}

4. By using the throw keyword you can declare only one exception at a time, but you can handle multiple exceptions by declaring them using the throws keyword. The throws keyword uses the comma(,) to separate the Exceptions.
throw:

void usingThrowKeyword() 
{
   //By using of throw keyword single exception is throwing
   throw new ArithmeticException("You can’t divide a number by zero.");
}

throws:

//By using of throws declaring multiple exceptions 
void myMethod() throws ArithmeticException, NullPointerException
{
    // handling exception
}

1 thought on “Difference between throw and throws in java”

Leave a Comment