Checked Exception
Checked Exception Interview with follow-up questions
1. What is a Checked Exception in Java?
A checked exception is one the compiler forces you to handle — you must either catch it or declare it with throws, or the code won't compile. In the class hierarchy, checked exceptions are subclasses of Exception but not of RuntimeException.
void readFile(String path) throws IOException { // declared
Files.readString(Path.of(path)); // may throw IOException (checked)
}
They represent recoverable, anticipated conditions outside your control — typically I/O, networking, or external resources (IOException, SQLException). The intent is to make the caller consciously decide how to handle a foreseeable failure.
The distinction and modern nuance interviewers want:
- Checked (
ExceptionminusRuntimeException) → compiler-enforced; unchecked (RuntimeExceptionandError) → not enforced, usually programming bugs. - Checked exceptions are controversial in modern Java: they don't compose well with lambdas/streams (a lambda can't throw a checked exception unless the functional interface declares it), so many current frameworks (notably Spring) favor unchecked exceptions and wrap checked ones (e.g. Spring's
DataAccessException). So while you must know how checked exceptions work, the modern trend leans toward unchecked exceptions for cleaner, functional-style code.
Follow-up 1
Can you provide an example of a checked exception?
Sure! An example of a checked exception in Java is the IOException. It is thrown when there is an error while performing input/output operations, such as reading from or writing to a file.
Follow-up 2
How does the compiler handle checked exceptions?
The compiler enforces the handling of checked exceptions by requiring the programmer to either declare the exception in the method signature using the 'throws' keyword or catch the exception using a try-catch block. If the programmer does not handle the checked exception, the code will not compile.
Follow-up 3
What is the difference between checked and unchecked exceptions?
The main difference between checked and unchecked exceptions in Java is that checked exceptions are checked at compile-time, while unchecked exceptions are not. Checked exceptions must be declared in the method signature or caught using a try-catch block, whereas unchecked exceptions do not require any handling. Examples of unchecked exceptions include NullPointerException and ArrayIndexOutOfBoundsException.
2. How do you handle a Checked Exception in Java?
You have two compiler-accepted options — handle it or propagate it:
- Catch and handle with
try-catch(usetry-with-resourcesfor closeables):
try (var reader = Files.newBufferedReader(path)) {
return reader.readLine();
} catch (IOException e) {
log.error("read failed", e);
throw new ReadException("Could not read " + path, e); // wrap & rethrow
}
- Declare and propagate with
throws, letting the caller deal with it:
String firstLine(Path path) throws IOException { ... }
Best practices interviewers reward:
- Don't swallow exceptions (empty
catchblocks hide failures) — at minimum log; ideally handle or rethrow. - Preserve the cause when wrapping (
new XException(msg, e)) so the stack trace isn't lost. - Use multi-catch (
catch (IOException | SQLException e)) for shared handling, andtry-with-resourcesto auto-close resources (replacing manualfinallycleanup). - Catch the most specific exception; never
catch (Exception e)blindly.
A current note: because checked exceptions don't play well with lambdas/streams, a common pattern is to wrap them in an unchecked exception (or use a helper) inside functional code — so handling a checked exception sometimes means translating it to an unchecked one at the boundary.
Follow-up 1
What is the syntax for handling checked exceptions?
The syntax for handling checked exceptions in Java is as follows:
try {
// code that may throw a checked exception
} catch (ExceptionType e) {
// code to handle the exception
}
Follow-up 2
Can you provide a code example of handling a checked exception?
Sure! Here's an example of handling a checked exception in Java:
try {
FileInputStream file = new FileInputStream("file.txt");
// code that may throw a FileNotFoundException
} catch (FileNotFoundException e) {
System.out.println("File not found");
}
Follow-up 3
What happens if a checked exception is not handled?
If a checked exception is not handled, it will result in a compilation error. The compiler will enforce that the exception is either caught and handled, or declared to be thrown by the method. If the exception is not caught and handled, and is not declared to be thrown, the code will not compile.
3. What are the advantages and disadvantages of Checked Exceptions?
Advantages
- Compiler-enforced handling — you can't accidentally ignore a foreseeable failure; the compiler makes you catch or declare it, which can improve reliability for genuinely recoverable conditions (I/O, network).
- Self-documenting API — a method's
throwsclause tells callers what can go wrong.
Disadvantages
- Boilerplate / clutter — propagating
throwsup many layers, or wrapping intry-catch, bloats code. - Leaky abstractions — a low-level
SQLExceptiondeclared on an interface forces every caller to know about it; changing internals can ripple through signatures. - Encourages bad habits — developers often swallow them (empty catch) or wrap in a generic
RuntimeExceptionjust to satisfy the compiler, defeating the purpose. - Poor fit with lambdas/streams — functional interfaces don't declare checked exceptions, so checked exceptions don't compose with
map/forEach, forcing awkward wrapping.
The 2026 framing interviewers want: checked exceptions are increasingly seen as a misfeature. Modern Java style (and frameworks like Spring, which uses unchecked DataAccessException) favors unchecked exceptions for cleaner, stream-friendly code, reserving checked exceptions for truly recoverable, caller-actionable conditions. So know the trade-off and lean toward unchecked + meaningful wrapping in new code.
Follow-up 1
Why would you choose to use a checked exception over an unchecked exception?
Checked exceptions are typically used when the exceptional condition is recoverable and the caller of the method is expected to handle the exception. By using checked exceptions, the programmer can enforce that the caller explicitly handles the exceptional condition, improving code reliability. Checked exceptions are useful in situations where the caller can take meaningful action to recover from the exception or provide an alternative course of action.
Follow-up 2
Can you provide a scenario where using a checked exception would be beneficial?
One scenario where using a checked exception would be beneficial is when performing file I/O operations. For example, when reading from a file, there might be a possibility of the file not being found or the file being corrupted. By using a checked exception, such as FileNotFoundException or IOException, the caller of the file reading method can handle these exceptional conditions and take appropriate action, such as displaying an error message to the user or retrying the operation.
Follow-up 3
What are the potential issues with using checked exceptions?
There are a few potential issues with using checked exceptions:
Inflexibility: Once a method declares a checked exception, all callers of that method must handle or declare the exception as well, even if they don't have a meaningful way to handle it. This can lead to unnecessary try-catch blocks or cluttered method signatures.
Overuse: Checked exceptions can be overused, leading to excessive handling and propagation of exceptions, which can make the code more complex and harder to maintain.
Inconsistent handling: Different methods may throw similar exceptions, but the handling of these exceptions may vary. This can lead to inconsistent error handling throughout the codebase.
Coupling: Checked exceptions can introduce coupling between the caller and the callee, as the caller needs to be aware of the specific checked exceptions thrown by the callee. This can make the code more tightly coupled and harder to refactor.
4. What are some common Checked Exceptions in Java?
Common checked exceptions (subclasses of Exception but not RuntimeException), grouped by area:
- I/O —
IOExceptionand its subclassesFileNotFoundException,EOFException,InterruptedIOException. - Database —
SQLException(JDBC). - Reflection / class loading —
ClassNotFoundException,NoSuchMethodException,NoSuchFieldException. - Concurrency —
InterruptedException(thrown byThread.sleep,join, blocking queue ops). - Cloning / parsing —
CloneNotSupportedException,ParseException.
try {
Class.forName("com.example.Driver"); // ClassNotFoundException (checked)
Thread.sleep(100); // InterruptedException (checked)
} catch (ClassNotFoundException | InterruptedException e) {
Thread.currentThread().interrupt(); // proper handling for InterruptedException
}
A couple of points interviewers like: InterruptedException is a frequent one in concurrency questions — the correct handling is usually to restore the interrupt flag (Thread.currentThread().interrupt()) rather than swallow it. And contrast these with common unchecked ones (NullPointerException, IllegalArgumentException, ArrayIndexOutOfBoundsException), which the compiler does not force you to handle. Knowing which exceptions are checked vs unchecked — and that I/O, SQL, reflection, and interruption are the classic checked ones — is exactly what's being tested.
Follow-up 1
What is the IOException and when is it thrown?
The IOException is a checked exception that is thrown when an input or output operation fails or is interrupted. It is typically thrown when there is an error in reading from or writing to a file, network connection, or any other input/output stream.
Follow-up 2
What is the ClassNotFoundException and when is it thrown?
The ClassNotFoundException is a checked exception that is thrown when an application tries to load a class through its string name using the Class.forName() method, but the class with the specified name cannot be found in the classpath.
Follow-up 3
What is the FileNotFoundException and when is it thrown?
The FileNotFoundException is a checked exception that is thrown when an application tries to open a file using the FileInputStream or FileReader classes, but the specified file does not exist or cannot be opened for reading.
5. Can we ignore a Checked Exception in Java?
Technically you can make the compiler stop complaining with an empty catch block, but doing so is a serious anti-pattern — "swallowing" an exception hides real failures and produces silent, hard-to-debug bugs:
try {
riskyIo();
} catch (IOException e) {
// ❌ empty catch — DON'T do this; the failure vanishes silently
}
So the honest answer is: you should not ignore a checked exception. The compiler forces you to acknowledge it (catch or declare), but acknowledging it with an empty catch is bad practice. Proper options:
- Handle it meaningfully (recover, retry, fall back).
- Log it (at minimum) so the failure is visible.
- Rethrow/wrap it — preserving the cause — so a higher layer can deal with it:
throw new AppException("...", e);
If a checked exception genuinely can't happen in your context, document why with a comment and rethrow it as an unchecked AssertionError/IllegalStateException rather than silently dropping it. Two related notes: for InterruptedException, "handling" means restoring the interrupt flag, not ignoring it; and a common reason people are tempted to swallow checked exceptions is that they don't fit lambdas/streams — the better fix there is to wrap them in an unchecked exception, not to silence them. The rule: never swallow exceptions.
Follow-up 1
What happens if we ignore a checked exception?
If we ignore a checked exception in Java, the exception will not be handled and the program will continue to execute. However, if the ignored exception is not caught by any other try-catch block, it will eventually propagate up the call stack and may cause the program to terminate.
Follow-up 2
Is it a good practice to ignore checked exceptions?
No, it is generally not considered a good practice to ignore checked exceptions. Checked exceptions are meant to indicate potential errors or exceptional conditions that should be handled by the calling code. Ignoring these exceptions can lead to unexpected behavior and make it difficult to diagnose and fix issues in the code.
Follow-up 3
What are the alternatives to ignoring a checked exception?
Instead of ignoring a checked exception, there are several alternatives that can be considered:
Handle the exception: This involves using a try-catch block to catch the exception and handle it appropriately. This could include logging the exception, displaying an error message to the user, or taking some other action to recover from the exception.
Propagate the exception: If the current method is not able to handle the exception, it can be propagated up the call stack by declaring the exception in the method signature using the 'throws' keyword. This allows the calling code to handle the exception or propagate it further.
Convert the exception: In some cases, it may be appropriate to convert a checked exception into an unchecked exception. This can be done by wrapping the checked exception in an unchecked exception, such as a RuntimeException, and throwing it. This can be useful when the calling code is not able to handle the checked exception, but still needs to be aware of the exceptional condition.
Live mock interview
Mock interview: Checked Exception
- Read your scene and goals
- Talk it out; goals tick off live
- Get a score and stronger lines
Your voice and your AI key never touch our servers; the key stays in this browser and is sent only to Google. Only your round scores are saved to track progress.