Hi, all: Here is the hierarchy of Exception related to array index errors. Exception __+--RuntimeException _______+-- IndexOutOfBoundsException ________________+-------ArrayIndexOutOfBoundsException ________________+-------StringIndexOutOfBoundsException Suppose you had a method X which could throw both array index and string index exceptions. Assuming that X does not hava any try-catch statements, which of the following statments are correct?
Thanks! [a]. The declaration for X must include "throws ArrayIndexOutOfBoundsException, StringIndexOutOfBoundsException". [b]. if a method calling X catches IndexOutOfBoundsException, both array and string index exceptions will be caught. [c]. if the declaration for X includes "throws IndexOutBoundsException", any calling method must use a try-catch block. [d].the declaration for X does not have to mention exceptions. Answer: [b], [d] The explaination about option 'c' & 'd' is [c]-- the significant word here is "must". Because these exceptions descend from RuntimeException, they do not have to be caught exen if declared by method X <Q1>: "they do not have to be caught", is it meaning that any calling method X can throw these exception to the method who calling them, so "they do not have to be caught" ? [d]--Because these exception descend from RuntimeException, they do not have to be declared. <Q2>:why? Something special for RuntimeException? Another <Q3>: What about the important difference between RuntimeException and CheckedException when catching them? Thanks! [ August 18, 2003: Message edited by: Roger Zhao ]
Questions 1 and 2: Yes! Runtime Exceptions are special cases. You can throw them without declaring that they can be thrown. If you had to declare them, then any method that worked with Objects would have to declare that it could throw a NullPointerException (which, too, is a RuntimeException) So, expressing this another way, all methods have an implicit "throws RuntimeException" modifier, since any method can throw one. Question 3: There is not difference when catching the exception. You would catch it just as you would catch a CheckedException.
Piscis Babelis est parvus, flavus, et hiridicus, et est probabiliter insolitissima raritas in toto mundo.
I believe the same holds true for Error as well, because it, like Exception and RuntimeException, descends from Throwable. Anything that's Throwable can be caught, though you probably wouldn't want to catch everything (especially errors). Regards, Jeff [ August 25, 2003: Message edited by: Jeff Bosch ]
Give a man a fish, he'll eat for one day. Teach a man to fish, he'll drink all your beer.
Cheers, Jeff (SCJP 1.4, SCJD in progress, if you can call that progress...)
All of the world's problems can be solved in a garden - Geoff Lawton. Tiny ad:
RavenDB is an Open Source NoSQL Database that’s fully transactional (ACID) across your database