SCJP Exception Handling and Java I/O 2 — Questions and Answers
Question 1: Which of the following is NOT a valid exception handling structure in Java?
- try-catch
- try-finally
- try-catch-finally
- catch-finally (without try) (Correct answer)
Correct answer: catch-finally (without try)
A `catch` or `finally` block cannot exist without a preceding `try` block — Java requires `try` to begin an exception handling structure.
Question 2: What is the difference between `Error` and `Exception` in Java?
- Errors are checked; Exceptions are unchecked
- Errors represent serious system-level problems not meant to be caught; Exceptions are application-level issues (Correct answer)
- Errors are thrown by the programmer; Exceptions by the JVM
- There is no difference
Correct answer: Errors represent serious system-level problems not meant to be caught; Exceptions are application-level issues
`Error` (e.g., `OutOfMemoryError`) signals serious JVM-level problems that programs typically cannot recover from, while `Exception` covers application-level issues.
Question 3: Which Java I/O class should be used to write primitive data types (int, double, boolean) to a stream?
- PrintWriter
- DataOutputStream (Correct answer)
- BufferedWriter
- ObjectOutputStream
Correct answer: DataOutputStream
`DataOutputStream` provides methods like `writeInt()`, `writeDouble()`, and `writeBoolean()` for writing primitive data types in a portable binary format.
Question 4: What is the try-with-resources statement used for in Java 7+?
- To handle multiple exceptions in one catch block
- To automatically close resources that implement AutoCloseable (Correct answer)
- To retry failed operations
- To log exceptions automatically
Correct answer: To automatically close resources that implement AutoCloseable
Try-with-resources automatically calls `close()` on any `AutoCloseable` resource declared in the try header when the block exits.
Question 5: In Java, can a single `catch` block catch multiple exception types?
- No, one catch per exception type always
- Yes, using a pipe (|) separator since Java 7 (multi-catch) (Correct answer)
- Yes, but only for RuntimeExceptions
- Yes, but only for checked exceptions
Correct answer: Yes, using a pipe (|) separator since Java 7 (multi-catch)
Java 7 introduced the multi-catch feature: `catch (IOException | SQLException e)` catches both exception types in one block.
Question 6: Which stream class in Java allows reading and writing to the same file simultaneously?
- FileInputStream
- FileOutputStream
- RandomAccessFile (Correct answer)
- BufferedStream
Correct answer: RandomAccessFile
`RandomAccessFile` supports both reading and writing to a file and allows the file pointer to be moved to any position.
Which of the following is NOT a valid exception handling structure in Java?