<%@ include file="../../ga4.jsp" %> Catching Java Exceptions - Quiz Explanation

Catching Java Exceptions - Quiz Explanation

The correct answers are indicated below, along with the text that explains the correct answers.
 
1. Examine the following snippet of code. What do you expect the output to be?
try {
   Integer number = new Integer("1");
   System.out.println("created a new Integer instance");
} catch (Exception e) {
   System.out.println("trouble in River City");
}

Please select the best answer.
  A. "created a new Integer instance"
  B. "trouble in River City"
  C. None of the Above
  The correct answer is A.
According to the API files for Java, and looking where Integer is defined in the lang package, there is a perfectly valid constructor that takes a String instance, such as "1". This will work fine and will not throw an exception.

2. Which pair of keywords must you use when invoking a method that might throw an exception?
Please select the best answer.
  A. throw, catch
  B. try, catch
  C. catch, finally
  The correct answer is B.
Yes, throw and catch are Java keywords relating to exceptions, but you only use throw if you are throwing an exception yourself. The keyword finally is optional. The two you must use are try and catch.

3. Select the answer that best describes the purpose of the following catch block:
try {
  // Write to file
  // Read from file
} 
catch (java.lang.IOException e) {
  // Do something if . . .
}
  A. Closes the file that has been written to and read.
  B. Catches an exception if the file is not available for reading or writing.
  C. Catches an exception if the System.getProperty call fails.
  The correct answer is B.
Exception occurs when an attempt is made to read or write to the file and the file does not exist.


Java Complete Reference