Difference between throw and throws in Java


Both throw and throws are the concepts of exception handing in which throw is used to explicitly throw an exception from a method or any block of code while throws are used in the signature of the method to indicate that this method might throw one of the listed type exceptions.

The following are the important differences between throw and throws.

Sr. No.Keythrowthrows
1DefinitionThrow is a keyword which is used to throw an exception explicitly in the program inside a function or inside a block of code.Throws is a keyword used in the method signature used to declare an exception which might get thrown by the function while executing the code.
2Internal implementationInternally throw is implemented as it is allowed to throw only single exception at a time i.e we cannot throw multiple exception with throw keyword.On other hand we can declare multiple exceptions with throws keyword that could get thrown by the function where throws keyword is used.
3Type of exceptionWith throw keyword we can propagate only unchecked exception i.e checked exception cannot be propagated using throw.On other hand with throws keyword both checked and unchecked exceptions can be declared and for the propagation checked exception must use throws keyword followed by specific exception class name.
4SyntaxSyntax wise throw keyword is followed by the instance variable.On other hand syntax wise throws keyword is followed by exception class names.
5DeclarationIn order to use throw keyword we should know that throw keyword is used within the method.On other hand throws keyword is used with the method signature.

Example of throw vs throws

JavaTester.java

 Live Demo

public class JavaTester{
   public void checkAge(int age){
      if(age<18)
         throw new ArithmeticException("Not Eligible for voting");
      else
         System.out.println("Eligible for voting");
   }
   public static void main(String args[]){
      JavaTester obj = new JavaTester();
      obj.checkAge(13);
      System.out.println("End Of Program");
   }
}

Output

Exception in thread "main" java.lang.ArithmeticException:
Not Eligible for voting
at JavaTester.checkAge(JavaTester.java:4)
at JavaTester.main(JavaTester.java:10)

Example

JavaTester.java

 Live Demo

public class JavaTester{
   public int division(int a, int b) throws ArithmeticException{
      int t = a/b;
      return t;
   }
   public static void main(String args[]){
      JavaTester obj = new JavaTester();
      try{
         System.out.println(obj.division(15,0));
      }
      catch(ArithmeticException e){
         System.out.println("You shouldn't divide number by zero");
      }
   }
}

Output

You shouldn't divide number by zero

Updated on: 18-Sep-2019

9K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements