0

Not able to understand the error

I wanted to check the functionality of throwing multiple exceptions. However below code is giving error that 'Unreported Exception'. can you please let me know what is wrong in code. public class Program { static int div(int a, int b) throws Exception, ArithmeticException { if(b == 0) { throw new ArithmeticException("Division by Zero"); } else { throw new Exception("Excption occured"); //return a / b; } } public static void main(String[] args) { System.out.println(div(42, 0)); } }

19th Dec 2020, 8:56 PM
Milind Ghag
Milind Ghag - avatar
3 Réponses
+ 1
When you throw an exception then it must be caught or declared to be thrown. You can catch it by a simple try catch block. public static void main(String[] args){ try{ System.out.println(div(42, 0)); } catch(Exception e){ System.out.print("Exception caught"); } } OR by using throws public static void main(String[] args) throws Exception { System.out.println(div(42,0)); }
19th Dec 2020, 9:29 PM
Avinesh
Avinesh - avatar
0
Avinesh Thank you for the reply.. However I have still one query that I have already used throws in 'div' method. If I remove throws Exception and keep only ArithmeticException and remove 'throw new Exception("Exception Occurred") then there is no error. So why is it not running successfully if I add throws Exception in div method. Why I need to use throws Exception along with main method
20th Dec 2020, 3:58 AM
Milind Ghag
Milind Ghag - avatar
0
"So why is it not running successfully if I add throws Exception in div method." > you mean "if I remove ".. so then you throw Exception and don't report it or catch. "Why I need to use throws Exception along with main method" > if div() does throw Exception and div() reports it by throws keyword, Someone stil must catch it, if main() do not it main() must report it by throws.
20th Dec 2020, 6:34 AM
zemiak