Main difference between throw
and throws
in Java is that throw
is used to throw an exception, whereas throws
is used to declare an exception.
When there is a checked exception then we need to handle it with throws
, while for unchecked exceptions we can have exception propagation with throw
keyword.
Following are the major differences between throw
and throws
in Java .
throw | throws |
throw keyword is used to throw an exception explicitly.
|
throws keyword is used to declare one or more exceptions, separated by comma.
|
Single exception is thrown by using throw .
|
Multiple exceptions can be thrown by using throws .
|
throw keyword is used within the method.
|
throws keyword is used with the method signature.
|
Syntax wise throw keyword is followed by the instance variable. | Syntax wise throws keyword is followed by exception class names. |
Checked exception cannot be propagated using throw . Unchecked exception can be propagated using throw .
|
For the propagation checked exception must use throws keyword followed by specific exception class name. |
public class Test { 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[]){ Test obj = new Test(); obj.checkAge(13); System.out.println("End Of Program"); } } OUTPUT ====== Exception in thread "main" java.lang.ArithmeticException: Not Eligible for voting at Test.checkAge(Test.java:5) at Test.main(Test.java:12)
public class Test { int division(int a, int b) throws ArithmeticException{ int t = a/b; return t; } public static void main(String args[]){ Test obj = new Test(); try{ System.out.println(obj.division(15,0)); } catch(ArithmeticException e){ System.out.println("can't divide number by zero"); } } } OUTPUT ====== can't divide number by zero
Hope you have enjoyed reading Difference between throw and throws in Java. Please do write us if you have any suggestion/comment or come across any error on this page. Thank you for reading!
Share this page on WhatsApp