SCJP Exception Handling and Java I/O 4 — Questions and Answers
Question 1: What happens when a finally block contains a return statement and the try block also contains a return statement?
- The try block's return value is used
- The finally block's return value overrides the try block's return value (Correct answer)
- A compile-time error occurs
- The method throws an exception
Correct answer: The finally block's return value overrides the try block's return value
The finally block's return statement overrides any return statement in the try or catch blocks.
Question 2: Which class provides methods to read primitive Java data types from an underlying input stream in a machine-independent way?
- BufferedInputStream
- DataInputStream (Correct answer)
- ObjectInputStream
- FilterInputStream
Correct answer: DataInputStream
DataInputStream implements DataInput and allows reading primitive types like readInt(), readDouble() in a portable way.
Question 3: What is the output of the following code? try { throw new RuntimeException(); } catch (Exception e) { System.out.print("caught"); throw e; } finally { System.out.print("finally"); }
- caught
- caughtfinally then re-throws (Correct answer)
- finally
- Compilation error
Correct answer: caughtfinally then re-throws
Both 'caught' and 'finally' are printed before the exception propagates to the caller.
Question 4: Which of the following is true about the FileWriter class?
- FileWriter extends Reader
- FileWriter writes bytes to a file
- FileWriter extends OutputStreamWriter (Correct answer)
- FileWriter cannot append to an existing file
Correct answer: FileWriter extends OutputStreamWriter
FileWriter extends OutputStreamWriter, which is a bridge from character streams to byte streams.
Question 5: Which exception is thrown when you try to access an element beyond the bounds of an array?
- IndexOutOfBoundsException
- ArrayIndexOutOfBoundsException (Correct answer)
- NegativeArraySizeException
- ArrayStoreException
Correct answer: ArrayIndexOutOfBoundsException
ArrayIndexOutOfBoundsException is specifically thrown when an array index is out of range.
Question 6: Which method of the InputStream class reads a single byte and returns it as an int in the range 0 to 255?
- readByte()
- read() (Correct answer)
- nextByte()
- fetch()
Correct answer: read()
The read() method of InputStream reads one byte and returns it as an int (0-255), or -1 at end of stream.
Question 7: What is the correct order of execution when an exception is thrown in a try block that has both catch and finally blocks?
- try → finally → catch
- try → catch → finally (Correct answer)
- catch → try → finally
- try → catch (only if exception)
Correct answer: try → catch → finally
When an exception occurs, control goes to the matching catch block, then finally always executes last.
What happens when a finally block contains a return statement and the try block also contains a return statement?