Java Magazine, Jan/Feb 2018
ORACLE COM JAVAMAGAZINE JANUARY FEBRUARY 2018 110 fix this However the remaining options all declare either IOException or a parent class of IOException Its important to note that a throws clause that mentions a parent exception class is suficient to encompass any child classes Because of this options A C and D all allow the code to compile correctly so how can you choose the best option among these When you declare an exception in a throws clause you impose an obligation on the caller of the method the caller must do something about the exception Also the throws clause is a form of description of the type of problems that can arise when calling the method These points both suggest that a throws clause should be as specific as possible To be more general or to mention irrelevant exceptions might place an additional burden on the caller by creating a perceived Testing equality between different types almost always returns false regardless of the contents requirement to handle situations that dont in fact arise Further additional generality will likely have the efect of hiding the real problem that might arise making it harder for the caller to know how to respond if an exception is reported On this basis its clear that option C which reports one unchecked exception OutOfMemoryError with a checked exception that cannot arise is unlikely to qualify as best Therefore option C is incorrect By the same arguments you can also see that option A which simply and vaguely reports that an Exception might arise is also less helpful than option D which gets directly to the point of reporting the single checked exception that could arise from the method As a result you can conclude that option A is incorrect and option D is the correct answer Theres another small point to consider as part of this discussion The question mentions that the method is final Why would that make any diference Its certainly a tenuous point in this case but it helps justify the best value judgment Often an abstract method in an interface declares a fairly general exception consider the close method in the AutoCloseable interface which throws Exception Given that such a method cannot possibly throw any exceptions because it doesnt have any implementation why would this be The answer is that its prohib
You must have JavaScript enabled to view digital editions.