Forums Register Login

Help with catching exception

+Pie Number of slices to send: Send
in K&B book at p.360:



it says "If there is no exception thrown in try block, execution transfers to // 4"

However, i just try:



--> compile error because IOException is never thrown in try {} even if try block may or may not throw an exception.

If I remove the first catch, the code compiles because Exception can catch any exception.

I just don't understand why the compiler fails. Why does it just let the second catch catches the exception? And I think the K&B book has a bug
+Pie Number of slices to send: Send
In this case the compiler was just too clever. There's no file or IO operation statement in the try block and so it knows that there can't be any IO specific errors. It shouts an error because you are trying to catch an exception that it knows is never gonna occur there.

+Pie Number of slices to send: Send
Just to add what has already said. You can't catch any specific checked exception (IOException is one of them) unless try block throws a one. But you can catch unchecked exceptions (RuntimeException).

Shin Kudo wrote:And I think the K&B book has a bug



It's not specifically mentioning which code inside the try block (in what you have posted), and what those exceptions are?


+Pie Number of slices to send: Send
 

Vijitha Kumara wrote:Just to add what has already said. You can't catch any specific checked exception (IOException is one of them) unless try block throws a one. But you can catch unchecked exceptions (RuntimeException).

Shin Kudo wrote:And I think the K&B book has a bug



It's not specifically mentioning which code inside the try block (in what you have posted), and what those exceptions are?




It's just a code to illustrate finally usage. But I think whatever the two exceptions are, if the try block does not throw an exception, then the compile will fail and of course, execution can not transfer to finally block.
Acetylsalicylic acid is aspirin. This could be handy too:
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com


reply
reply
This thread has been viewed 716 times.
Similar Threads
Finally
Exception Question
try-catch-finally
Exception doubt
Exceptions - Question
More...

All times above are in ranch (not your local) time.
The current ranch time is
Mar 28, 2024 13:18:18.