SCJP Exception Handling and Java I/O 1 — Questions and Answers
Question 1: Which of the following is a checked exception in Java?
- NullPointerException
- ArrayIndexOutOfBoundsException
- IOException (Correct answer)
- ClassCastException
Correct answer: IOException
`IOException` is a checked exception that must be declared with `throws` or handled with a `try-catch` block.
Question 2: What is the purpose of the `finally` block in Java exception handling?
- It executes only when an exception is thrown
- It executes only when no exception is thrown
- It always executes after try/catch, regardless of outcome (Correct answer)
- It replaces the catch block
Correct answer: It always executes after try/catch, regardless of outcome
The `finally` block executes unconditionally after the `try` and any matching `catch` blocks, making it ideal for cleanup code.
Question 3: Which keyword is used to manually throw an exception in Java?
- throws
- throw (Correct answer)
- raise
- exception
Correct answer: throw
The `throw` keyword is used to explicitly throw an exception object within a method body.
Question 4: What happens if an exception is thrown inside a `finally` block?
- It is silently ignored
- It replaces any exception from the try/catch block (Correct answer)
- The program crashes immediately
- A second finally block handles it
Correct answer: It replaces any exception from the try/catch block
An exception thrown inside a `finally` block propagates upward and discards any exception that was in progress from the `try` block.
Question 5: Which class is the parent of all errors and exceptions in Java?
- Exception
- Error
- RuntimeException
- Throwable (Correct answer)
Correct answer: Throwable
`Throwable` is the root of the Java exception hierarchy — both `Error` and `Exception` extend it.
Question 6: In Java I/O, which class is used for reading characters from a file efficiently with buffering?
- FileInputStream
- FileReader
- BufferedReader (Correct answer)
- DataInputStream
Correct answer: BufferedReader
`BufferedReader` wraps a `Reader` (like `FileReader`) to provide buffered character reading and the convenient `readLine()` method.
Which of the following is a checked exception in Java?