1.

What is the difference between the ‘throw’ and ‘throws’ keyword in java?

Answer»
  • The ‘throw’ keyword is used to manually throw the exception to the calling method.
  • And the ‘THROWS’ keyword is used in the FUNCTION definition to inform the calling method that this method throws the exception. So if you are calling, then you have to handle the exception.

Example - 

class Main { public static int testExceptionDivide(int a, int b) throws ArithmeticException{ if(a == 0 || b == 0) throw new ArithmeticException(); return a/b; } public static void main(String args[]) { try{ testExceptionDivide(10, 0); } CATCH(ArithmeticException e){ //Handle the exception } }}

Here in the above snippet, the method testExceptionDivide throws an exception. So if the main method is calling it then it MUST have handled the exception. Otherwise, the main method can ALSO throw the exception to JVM.

And the method testExceptionDivide 'throws’ the exception based on the condition.



Discussion

No Comment Found