Q1. Inspect the API documentation for the java.util.Scanner class and: a) Identi
ID: 3721629 • Letter: Q
Question
Q1. Inspect the API documentation for the java.util.Scanner class and:
a) Identify two methods that can throw an Exception (NOTE: pick methods for which you can think of an example programming use case since you will need to use them later!)
b) Write down the two method signatures. Also, for one of the possible exceptions that each method can throw (if it throws more than one you only need to chose one) identify and write down the nearest (direct) exception superclass that it extends.
c) Explain why the exception class hierarchy is significant and what effect it will have on program compilation and execution.
Explanation / Answer
Ans:
Throws:
InputMismatchException - if the next token does not match the Float regular expression, or is out of range
NoSuchElementException - if the input is exhausted
IllegalStateException - if this scanner is closed
exception class hierarchy
It is important to know the hierarchy of exception classes in order to write correct programs. The class Exception lies at the root of the exception hierarchy. Every exception type in Java is a subclass of Exception. Therefore, a catch clause designed to handle Exception can process all pre-defined exceptions of Java. However, in addition to the subclasses of Exception, we have subclasses of Error which represents a condition that generally cannot be handled by the programmer. The exceptions that inherit from Error denote serious errors like VirtualMachineError from which a program cannot normally recover. Though it is syntaxialy correct to catch Errors also, one however should refrain from doing so. Both, Exception and Error are subclasses of Throwable. (We have both Throwable class and Throwable interface).
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.