SCJP Exception Handling and Java I/O 5 — Questions and Answers
Question 1: Which statement about checked exceptions is correct?
- They extend RuntimeException
- They must be caught or declared in the method signature using throws (Correct answer)
- They can never be caught
- They are subclasses of Error
Correct answer: They must be caught or declared in the method signature using throws
Checked exceptions must either be handled with a try-catch or declared with the throws keyword in the method signature.
Question 2: Which class should you use to efficiently write characters to a file using a buffer?
- FileWriter
- PrintWriter
- BufferedWriter (Correct answer)
- CharArrayWriter
Correct answer: BufferedWriter
BufferedWriter wraps a Writer and uses an internal buffer to reduce I/O operations, improving performance.
Question 3: What does the try-with-resources statement require of the resources it manages?
- They must implement Serializable
- They must implement AutoCloseable (Correct answer)
- They must extend InputStream
- They must be declared as final
Correct answer: They must implement AutoCloseable
Resources used in try-with-resources must implement the AutoCloseable interface so close() can be called automatically.
Question 4: Which exception is thrown when the JVM cannot find the definition of a class that is referenced at runtime?
- ClassNotFoundException
- NoClassDefFoundError (Correct answer)
- ClassCastException
- InstantiationException
Correct answer: NoClassDefFoundError
NoClassDefFoundError is thrown when a class was present at compile time but cannot be found at runtime.
Question 5: What is the purpose of the ObjectOutputStream class?
- To write formatted text output
- To serialize Java objects to an output stream (Correct answer)
- To write raw bytes to a file
- To convert objects to XML
Correct answer: To serialize Java objects to an output stream
ObjectOutputStream serializes Java objects (that implement Serializable) by writing them as a byte stream.
Question 6: Which of the following exceptions is an unchecked exception?
- IOException
- SQLException
- NullPointerException (Correct answer)
- ClassNotFoundException
Correct answer: NullPointerException
NullPointerException extends RuntimeException, making it unchecked; the compiler does not require it to be caught or declared.
Question 7: When multiple exceptions are caught in a single catch block using multi-catch (Java 7+), which statement is true?
- The caught exception variable is effectively final (Correct answer)
- You can reassign the caught exception variable
- Only two exceptions can be combined in one catch
- Multi-catch requires all exceptions to share a common superclass
Correct answer: The caught exception variable is effectively final
In a multi-catch block, the exception parameter is implicitly final and cannot be reassigned.
Which statement about checked exceptions is correct?