aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes please explain the output of the code below 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 "please explain the output of the code below" Watch "please explain the output of the code below" New topic
Author

please explain the output of the code below

Rituka Jaiswal
Greenhorn

Joined: Sep 27, 2011
Posts: 6
01. class BadObjectException extends Exception {}
02. class BadIndexException extends IndexOutOfBoundsException {}
03.
04. public class Test {
05.
06. public void doSomething() {}
07.
08. public void aMethod() {
09. try {
10. doSomething();
11. }catch(BadIndexException be) {
12. System.out.println("BadIndexException");
13. throw new BadIndexException(){};
14. }
15. }
16.
17. public void anotherMethod() throws BadObjectException{
18. try {
19. doSomething();
20. }catch(BadObjectException be) {
21. System.out.println("BadObjectException");
22. }
23. }
24.
25. public static void main(String[] args) throws BadObjectException{
26. Test t = new Test();
27. t.aMethod();
28. t.anotherMethod();
29. }
30. }

the output is that metnod anotherMethod() would not compile.
Tommy Delson
Ranch Hand

Joined: Apr 13, 2011
Posts: 206


The problem is you've violated a Declare and Handle rules.

See my comments in code below for more insight...hope it help.








Go back and reread Chapter 5, page 415 on "Rethrowing the Same Exception (Exam Objectives 2.4 and 2.5)" topic to reinforce and confirm your knowledge.

Here is a brief recap from K & B book:


All other catch clauses associated with the same try are ignored, if a finally
block exists, it runs, and the exception is thrown back to the calling method (the
next method down the call stack). If you throw a checked exception from a catch
clause, you must also declare that exception! In other words, you must handle and
declare, as opposed to handle or declare. The following example is illegal:



In the preceding code, the doStuff() method is clearly able to throw a checked
exception—in this case an IOException—so the compiler says, "Well, that's just
peachy that you have a try/catch in there, but it's not good enough. If you might
rethrow the IOException you catch, then you must declare it!"











OCPJP6-05-11
"Your life is in your hands, to make of it what you choose."
Rituka Jaiswal
Greenhorn

Joined: Sep 27, 2011
Posts: 6
I get it now..
 
 
subject: please explain the output of the code below