Difference between Throw and Throws in java

There are plethora of differences between Throw and Throws keywords. A list of differences between throw and throws in java are given below:

No.ThrowThrows
1)Java throw keyword is used to explicitly throw an exception.Java throws keyword is used to declare an exception.
2)Checked exception cannot be propagated using throw only.Checked exception can be propagated with throws.
3)Throw is followed by an instance.Throws is followed by class.
4)Throw is used within the method.Throws is used with the method signature.
5)You cannot throw multiple exceptions.You can declare multiple exceptions e.g.
public void method()throws IOException,SQLException.
6)Checked exception cannot be propagated using
throw only.Unchecked exception can be propagated
using throw.
For the propagation checked exception
must use throws keyword followed by
specific exception class name.

Use of Throw : throw keyword is used inside a function. It is used when it is required to throw an Exception logically.


void Demo() throws ArithmeticException, NullPointerException
{
// Statements where exceptions might occur.
throw new ArithmeticException();
}

Use of Throws : throws keyword is in the function signature. It is used when the function has some statements that can lead to some exceptions.

void Demo()
{
// Statements where exceptions might occur.
}

Syntax of Throw :  Syntax of throw keyword includes the instance of the Exception to be thrown.

// throwing instance of IOException
throw new IOException();
 

Syntax of Throws : Syntax of throws keyword includes the class names of the Exceptions to be thrown.

// throwing multiple exceptions by class names
void Demo() throws ArithmeticException, NullPointerException
{
// Statements where exceptions might occur.
}

Example 1 : Throw 

public class GFG {
  public static void main(String[] args)
  {
   // Use of unchecked Exception
   try {
    // double x=3/0;
    throw new ArithmeticException();
   }
   catch (ArithmeticException e) 
   {
     e.printStackTrace();
   }
  }
}

output : 
java.lang.ArithmeticException: / by zero
    at UseOfThrow.main(UseOfThrow.java:8)

Example 2 : Throws

import java.io.IOException;
  
public class UseOfThrowAndThrows {
  
    public static void main(String[] args) 
        throws IOException
    {
    }
}

Output : 
Exception in thread "main" java.io.IOException
    at UseOfThrowAndThrows.main(UseOfThrow.java:7)

useful links for java : click here

Leave a Comment

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