• Post Reply Bookmark Topic Watch Topic
  • New Topic

Help with catching exception  RSS feed

 
Shin Kudo
Greenhorn
Posts: 25
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Vishwanath Krishnamurthi
Ranch Hand
Posts: 331
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.

 
Vijitha Kumara
Bartender
Posts: 4001
42
Chrome Fedora Hibernate
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?


 
Shin Kudo
Greenhorn
Posts: 25
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!