Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Doubt in Exception Handling.

 
Suresh Rajadurai
Ranch Hand
Posts: 58
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Folks,

Please see the following 2 programs. could you please explain me why program 1 is giving compilation errors(complaining that it is expecting catch block) while program 2 is working fine without the catch block.

Only difference is , method in program 1 is void return type, whereas method in program 2 is integer return type. Is it permitted to avoid having a catch block in the method if the return type of the method is NOT void? I am confused.

Program 1:



Program 2:




Much appreciated,

thanks in advance,

Suresh.
 
Ankit Garg
Sheriff
Posts: 9521
22
Android Google Web Toolkit Hibernate IntelliJ IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Well the first program is going to throw a checked exception to the calling method. So you need to either catch it or use a throws clause with the method. The second code will also throw a checked exception, but the return statement in the finally block will suppress that exception. So you don't need a catch block. I would recommend that you try these two modified versions of the first program



 
mansi gupte
Ranch Hand
Posts: 72
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
new test().method(); is it a valid statement?
 
Vijitha Kumara
Bartender
Posts: 3913
9
Chrome Fedora Hibernate
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
piya rai wrote:new test().method(); is it a valid statement?


well, what do you think it should be?
 
Vikas Kapoor
Ranch Hand
Posts: 1374
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
piya rai wrote:new test().method(); is it a valid statement?

It's perfectly valid statement.
you can think it in this way also.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic