can someone please tell me why the following code snippet is illegal AND what is the correction to be made ?
I tried making a full program using 'ArithmeticException' instead of IO, as shown below and it compiles. However, when i put IOException in place of ArithmeticException in the above program, i get a compile-time error.
Please help me to understand what is happening here ?
PS : How do i present/format my code on this website the way an IDE does it ?
Please tell us the details; what sort of code did you have in your blocks? Which compiler error did you suffer? In the cases of Exceptions, they are usually informative. And have a look at the Java™ Tutorials, particularly the section about "catch or specify requirement".
If you're getting the error, "cannot find symbol" for "IOException," then it's probably because you're missing an import statement, since IOException is in the package java.io. This error would NOT apply to ArithmeticException, because ArtihmeticException is in java.lang, which is automatically imported.
Beyond that, I would also expect the error, "unreported exception java.io.IOException..." This is because you are explicitly throwing an Exception in your catch block, but not handing it (re-catching it or declaring it) elsewhere. This error would NOT apply to ArithmeticException because ArithmeticException is a subclass of RuntimeException, which is "unchecked" (meaning the complier does not require handling for it).
I would also expect the error, "exception java.io.IOException is never thrown in body of corresponding try statement." This is because the compiler is smart enough to know that nothing in your try block can throw an IOException. I'm not sure why the compiler doesn't do the same for ArithmeticException. It might be because ArithmeticException is unchecked. On the other hand, I'm not sure this check is comprehensive, so... I don't know.
"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer sscce.org
Happiness is not a goal ... it's a by-product of a life well lived - Eleanor Roosevelt. Tiny ad: