File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes Doubt in Exception Handling. Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Doubt in Exception Handling." Watch "Doubt in Exception Handling." New topic

Doubt in Exception Handling.

Suresh Rajadurai
Ranch Hand

Joined: Feb 22, 2007
Posts: 58
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,

Ankit Garg

Joined: Aug 03, 2008
Posts: 9465

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

SCJP 6 | SCWCD 5 | Javaranch SCJP FAQ | SCWCD Links
mansi gupte
Ranch Hand

Joined: Dec 30, 2008
Posts: 72
new test().method(); is it a valid statement?
Vijitha Kumara

Joined: Mar 24, 2008
Posts: 3902

piya rai wrote:new test().method(); is it a valid statement?

well, what do you think it should be?

[How to ask questions] [Twitter]
Vikas Kapoor
Ranch Hand

Joined: Aug 16, 2007
Posts: 1374
piya rai wrote:new test().method(); is it a valid statement?

It's perfectly valid statement.
you can think it in this way also.
I agree. Here's the link:
subject: Doubt in Exception Handling.
It's not a secret anymore!