wood burning stoves 2.0*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Exception Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Exception" Watch "Exception" New topic
Author

Exception

jibs parap
Ranch Hand

Joined: Dec 07, 2004
Posts: 134
Checked exception(s) that a method can throw MUST BE declared.
Each method MUST either handle(try-catch) or declare checked excption(s).

- taken from K&B
---------------
I think these 2 sentences contradict themselves. One says you should declare it but the other says you can get away without declaring if you handle it.

I'd be happy if someone can explain this.

Thanks
jibs parap
Ranch Hand

Joined: Dec 07, 2004
Posts: 134
as a continuation to the above:

- declare exception means by declaring it by using 'throws'?
- though its 'handle or declare' rule, no harm in doing both?
wise owen
Ranch Hand

Joined: Feb 02, 2006
Posts: 2023
If a method might throw a checked exception, it must be declared in the signature of the method (as throws ). Unchecked exceptions do not have to be listed in the method header.

If code calls a method that may throw a checked exception, the calling code must handle the exception. It can handle the exception by either catching it or by declaring in its own signature that it may throw that exception type. Unchecked exceptions do not have to be handled by calling code.
Burkhard Hassel
Ranch Hand

Joined: Aug 25, 2006
Posts: 1274
Hi cowboys,

checked exceptions must either be handled OR declared.

jibs parap posted October 21, 2006 06:38 PM
- declare exception means by declaring it by using 'throws'?
- though its 'handle or declare' rule, no harm in doing both?

first: yes
second: exactly, doesn't harm doing both.


In the K&B book it is said that a checked exception that is rethrown in the catch block has to be both handled and declared, but I think this is wrong, handling it will do the job. But that will lead to some ugly nesting:


compiles without warning and prints: main ready



Yours,
Bu.


all events occur in real time
jibs parap
Ranch Hand

Joined: Dec 07, 2004
Posts: 134
Originally posted by wise owen:
[QB]If a method might throw a checked exception, it must be declared in the signature of the method (as throws ).

But if you handle it(using try and catch)in the same method, you don't need to declare it.
That means declaration is only OPTIONAL, NOT A MUST; am I right?
Mike Ngo
Ranch Hand

Joined: Oct 16, 2006
Posts: 89
1) If you don't handle it, you MUST declare
2) if you handle it, you don't have to declare it. You can declare it but it is redundant.
 
wood burning stoves
 
subject: Exception