What is the need of throws here.the program is working without throws also. | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 3

What is the need of throws here.the program is working without throws also.

int div(int a, int b) throws ArithmeticException { if(b == 0) { throw new ArithmeticException("Division by Zero"); } else { return a / b; } }

23rd Nov 2016, 2:37 PM
somnath
somnath - avatar
4 Answers
+ 4
throws a keyword which is used as definition of method it tells the program that this method is execpected to throw and catch and methods I don't know if it works on without it as b as 0 does that work
23rd Nov 2016, 3:47 PM
Sandeep Chatterjee
+ 2
In IDE's when you write your code, they usually show the exceptions for methods tagged with the 'throws' keyword. Since ArithmeticException is an unchecked exception, it would not be needed to use 'throws' for it, but this code would suggest, that you really should care about and calculate with ArithmeticException while using the given method. I think this is the same case as the @Deprecated annotation. It has no real purpose, but rather a warning. But why can use.. ? I think, mainly because of syntax rules, the 'throws' keyword was written to be used with exception types after it, and this also matches. Similarly, the 'x = x;' codeline, it basically does nothing.
23rd Nov 2016, 3:55 PM
Magyar Dávid
Magyar Dávid - avatar
+ 1
I am not talking about throw.it throws
23rd Nov 2016, 3:40 PM
somnath
somnath - avatar
+ 1
do you have to use throws only when there is throw.
23rd Nov 2016, 3:49 PM
somnath
somnath - avatar