This week's book giveaway is in the Performance forum.
We're giving away four copies of The Java Performance Companion and have Charlie Hunt, Monica Beckwith, Poonam Parhar, & Bengt Rutisson on-line!
See this thread for details.
Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Try catch block.....

 
Parameswaran Thangavel
Ranch Hand
Posts: 485
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
i didn't understand why there is compiler error in the second case....






output:

No compiler error. The lines "Before Try" and "At the end" are printed on the screen.





output:

Compiler error complaining about the catch block where no IOException object can ever be thrown.
 
Joe Sondow
Ranch Hand
Posts: 195
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The compiler doesn't mind if you try to catch Exception or Throwable because what you might be catching is an unchecked exception that the compiler is not going to look for in your code. For example, something in the try block might throw a RuntimeException or an Error which would be caught by catch (Throwable t). The compiler doesn't care whether there's anything in the try block that could throw either of those. It just assumes that it's possible.

However, when you specify that you are catching something that can only be a checked exception, such as IOException, then the compiler will only allow it if it actually might be thrown by code in the try block.
[ May 05, 2005: Message edited by: Joe Sanowitz ]
 
Jas Oberai
Ranch Hand
Posts: 231
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Joe,can you please explain this with some code,i toowant to clarify my doubts!!
 
Parameswaran Thangavel
Ranch Hand
Posts: 485
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi joe

let me tell what i understand

if we are cathching only those exceptions subclass to Exception class and too not RuntimeException, then only the compiler will look for the code inside the try block..

my doubt is
for instance if i am catching IOException then is it mandatory for us to put some code relating to some I/O operations inside the try block...
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic