Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Exception

 
jibs parap
Ranch Hand
Posts: 134
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 134
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 2023
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 1274
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
jibs parap
Ranch Hand
Posts: 134
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 89
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic