Java Exception Handling Interview Questions
Last updated 2026-11-19
Exception handling looks easy until an interviewer shows you a try block with a return, a finally block that throws, and a catch order that does not compile. These questions test whether you know the exact rules, not just the vocabulary.
Below are the standard concept questions and the code puzzles that follow them, with outputs verified against Java 17 behaviour. Pair this with Java OOP questions because overriding rules interact with checked exceptions.
| Root type | Throwable, with Error and Exception below it |
|---|---|
| Checked | Exception except RuntimeException branch |
| Java version | 17 and later |
The hierarchy in one list
- Throwable has two children: Error (serious JVM problems such as OutOfMemoryError, usually not caught) and Exception.
- RuntimeException and its subclasses (NullPointerException, IllegalArgumentException, ArithmeticException) are unchecked.
- All other Exception subclasses (IOException, SQLException) are checked and must be caught or declared.
Java Exception Handling Interview Questions: questions with worked answers
1 Explain checked versus unchecked exceptions and when to use each.
easyChecked exceptions extend Exception but not RuntimeException; the compiler forces the caller to catch or declare them. Unchecked exceptions extend RuntimeException or Error and need no declaration. Use checked exceptions for recoverable conditions a caller can reasonably handle, such as a missing file, and unchecked for programming errors such as a null argument or an illegal state. Many modern frameworks, including Spring, favour unchecked exceptions to avoid cluttering signatures.
2 What is the difference between throw and throws?
easythrow is a statement that raises a specific exception object at that point. throws is part of a method signature and lists the checked exceptions the method may let escape. A method can declare throws without ever using throw, because it may call something else that throws.
3 Predict the output: return inside try with finally.
mediumThe finally block always runs, and if it returns, that value replaces the try value and discards any exception in flight. Here the method returns 2, not 1, and the exception thrown in try is lost. Most linters flag a return in finally for that reason.
javastatic int f() { try { throw new RuntimeException("boom"); } catch (RuntimeException e) { return 1; } finally { return 2; // overrides the return in catch } } public static void main(String[] a) { System.out.println(f()); } // 24 Does finally always run? When does it not?
mediumIt runs after normal completion, after an exception and after return, break or continue. It does not run if the JVM exits via System.exit() or Runtime.halt(), if the process is killed, if the thread is killed or the machine loses power, if the JVM crashes, or if the thread stays blocked forever or loops infinitely inside the try.
5 What does this print? Exception thrown from finally.
mediumIf both the try block and finally throw, the exception from finally wins and the original is lost unless you saved it. Try-with-resources avoids this by recording the lost exception as a suppressed exception.
javatry { try { throw new IllegalStateException("try"); } finally { throw new RuntimeException("finally"); } } catch (Exception e) { System.out.println(e.getMessage()); // finally }6 How does try-with-resources work, in what order are resources closed and what is a suppressed exception?
mediumAny resource declared in the header that implements AutoCloseable is closed automatically at the end, in reverse order of declaration, before any catch or finally block runs. If the body throws and close also throws, the body exception is the primary one and the close exception is attached through getSuppressed(). A null resource is simply skipped.
javaclass R implements AutoCloseable { final String n; R(String n) { this.n = n; System.out.println("open " + n); } public void close() { System.out.println("close " + n); } } try (R a = new R("A"); R b = new R("B")) { System.out.println("body"); } // open A, open B, body, close B, close A7 Which catch ordering compiles? What is multi-catch?
mediumA catch for a subclass must come before its superclass, otherwise the compiler reports that the exception has already been caught. Multi-catch (catch (IOException | SQLException e)) handles unrelated types in one block; the alternatives cannot be related by inheritance, and the variable is implicitly final. Catching a checked exception that the try body cannot throw is also a compile error, except for Exception and Throwable.
8 How do you write a custom exception and chain a cause?
mediumExtend Exception for a checked type or RuntimeException for an unchecked type, give it constructors that accept a message and a cause, and pass the original exception along so the stack trace shows both. Never discard the cause.
javaclass OrderException extends RuntimeException { OrderException(String msg, Throwable cause) { super(msg, cause); } } try { Integer.parseInt("abc"); } catch (NumberFormatException e) { throw new OrderException("Invalid quantity", e); }9 What are the rules for overriding a method that throws exceptions?
hardAn overriding method may throw no checked exceptions, the same ones, or narrower subclasses of those declared by the parent. It may not throw a new or broader checked exception. It may throw any unchecked exception. If the parent method declares none, the child cannot declare a checked one, which is why a Runnable lambda cannot throw IOException.
10 Can you catch StackOverflowError or OutOfMemoryError?
mediumBoth are Errors and technically catchable, but recovery is rarely reliable. A StackOverflowError after deep recursion can be caught and the stack unwinds, but the code that triggered it is usually buggy and should be rewritten iteratively. After OutOfMemoryError the JVM may be unable to allocate anything to handle it. Production systems prefer to log, run -XX:+HeapDumpOnOutOfMemoryError and restart.
11 What is ExceptionInInitializerError?
mediumIf a static initialiser or static field initialiser throws, the class initialisation fails and the JVM throws ExceptionInInitializerError wrapping the cause. Every later attempt to use the class throws NoClassDefFoundError because the class is marked as erroneous.
javaclass Config { static int v = Integer.parseInt("x"); // NumberFormatException } // first use of Config: java.lang.ExceptionInInitializerError // next use of Config: java.lang.NoClassDefFoundError12 What do 5 / 0 and 5.0 / 0 give?
easyInteger division by zero throws ArithmeticException with the message "/ by zero". Floating point division follows IEEE 754 and returns Infinity (or NaN for 0.0 / 0.0) without any exception. Also, 5 % 0 throws for ints while 5.0 % 0 gives NaN.
13 What are helpful NullPointerException messages?
mediumSince Java 14, enabled by default from Java 15, the JVM describes exactly what was null, for example: Cannot invoke "String.length()" because "s" is null. This removes much of the guessing in long chains like a.b().c(). Optional and Objects.requireNonNull(x, "message") are still the right way to state your intent.
14 What is the best practice for catching and logging exceptions?
mediumCatch the most specific type you can handle, never leave an empty catch block, do not catch Throwable, and log or rethrow but not both, or the same failure appears several times in logs. Wrap with context when crossing layers. Clean up with try-with-resources. Do not use exceptions for ordinary control flow, since creating a stack trace is expensive.
15 How do checked exceptions interact with lambdas and streams?
hardStandard functional interfaces such as Function and Runnable declare no checked exceptions, so a lambda body that calls a method throwing IOException will not compile. Either catch inside the lambda and wrap in an unchecked exception, or define your own functional interface with a throws clause and a small adapter. See streams and lambdas.
javaList<String> paths = List.of("a.txt"); paths.forEach(p -> { try { java.nio.file.Files.readString(java.nio.file.Path.of(p)); } catch (java.io.IOException e) { throw new java.io.UncheckedIOException(e); } });
Frequently asked questions
What is the difference between Error and Exception?
Errors indicate serious JVM-level problems that applications generally cannot recover from. Exceptions describe conditions that an application might handle.
Is it good practice to catch Exception?
Only at boundaries, such as a request handler that must turn every failure into a response. Inside business code catch specific types.
Can a try block exist without catch?
Yes, if it has a finally block or is a try-with-resources.
How are exceptions asked in coding rounds?
Mostly as output prediction with finally and return, and as design questions on custom exceptions. See Java interview questions for more output puzzles.
Related guides
More in Programming Language Interview Questions by Language
- Java Garbage Collection Interview Questions
- Java Generics Interview Questions
- Java HashMap Internals Interview Questions
- Java Interfaces and Abstract Classes Interview Questions
- Java Interview Questions and Answers
- Java Multithreading Interview Questions
- Java OOPs Interview Questions
- Java String Interview Questions
- JavaScript Array Methods Interview Questions
- JavaScript Closures Interview Questions
- JavaScript Coding Interview Questions with Solutions
- JavaScript DOM Interview Questions