Interview Q&A · Java · 8 questions in this topic
Exceptions, Errors and Handling Strategies — Java Interview Q&A
What exceptions and errors are, why handling matters, and the basic strategies Java provides for dealing with failure. Part of Exception Handling · 294 questions in the Java bank.
What is an exception in Java?
Answer
An exception is an object that represents an abnormal event which disrupts the normal flow of a program. It is created either by the JVM when a runtime problem occurs or explicitly by application code. Every exception is an instance of a class rooted at java.lang.Throwable, with most application failures modeled as subclasses of java.lang.Exception.
Key points
- 1An exception carries a type, a message, and a stack trace describing where it occurred.
- 2It can be raised by the JVM, by library code, or by explicit throw statements.
- 3All standard exception classes live in java.lang, so no import is needed.
Example
int[] a = new int[3]; int x = a[5]; // throws ArrayIndexOutOfBoundsException at runtime
In what situations do exceptions arise?
Answer
Common triggers include accessing an array with an invalid index, parsing a malformed number which throws NumberFormatException, casting an object to an incompatible type which throws ClassCastException, and dereferencing a null reference. Illegal method arguments and IO failures such as a missing file or a broken connection are other frequent causes. Trying to instantiate an interface or abstract class with new is a compile error rather than a runtime exception, although reflective creation can throw InstantiationException.
Key points
- 1ArrayIndexOutOfBoundsException from a bad array index.
- 2NumberFormatException from parsing invalid text such as Integer.parseInt("abc").
- 3ClassCastException from an illegal cast and NullPointerException from a null dereference.
- 4IllegalArgumentException from bad parameters and IOException from IO failures.
What is exception handling?
Answer
Exception handling is the mechanism Java provides for responding to runtime problems without letting the program terminate abruptly. Code that might fail is guarded so that when an exception occurs, control transfers to a handler that can log the problem, clean up, recover, or report a clear error. This separation keeps the normal success path readable and isolates recovery logic in dedicated blocks.
What is an Error in Java?
Answer
An Error represents a serious problem at the JVM or environment level that an application is not expected to recover from. Typical examples are OutOfMemoryError when the heap is exhausted and StackOverflowError from runaway recursion. Error extends Throwable directly rather than Exception, so it is not an Exception, and application code generally lets such problems propagate instead of catching them.
Key points
- 1Errors signal environment or JVM failures, not ordinary application mistakes.
- 2Examples include OutOfMemoryError, StackOverflowError, and NoClassDefFoundError.
- 3Catching Error is legal but rarely useful, since recovery is usually impossible.
What are the advantages of exception handling?
Answer
The main benefit is that a program can survive runtime problems instead of terminating abruptly at the first failure. Typed exception classes carry precise information about what went wrong, which makes diagnosis and recovery easier than checking raw error codes. Propagation up the call stack also lets the failure surface at a level that has enough context to handle it, rather than forcing every low level method to deal with it.
Key points
- 1Normal logic and error recovery stay separate, so code is cleaner.
- 2Specific catch blocks can react differently to different failure types.
- 3Unhandled failures propagate to a caller that is better placed to decide what to do.
In how many ways can exceptions be handled?
Answer
There are two classic options: catch the exception locally with a try-catch block, or declare it in the method signature with throws so the caller becomes responsible for it. Modern Java adds a third practical form, try-with-resources, which both guards the code and closes declared resources automatically. In all cases the goal is either to handle the failure where it occurs or to propagate it to code that can.
Example
try (java.io.BufferedReader br = new java.io.BufferedReader(new java.io.FileReader("data.txt"))) { System.out.println(br.readLine()); } catch (java.io.IOException e) { System.err.println("Read failed: " + e.getMessage()); }
Name five keywords related to exception handling.
Answer
The five core keywords are try, catch, finally, throw, and throws. The try block marks guarded code, catch handles a specific failure type, and finally holds cleanup code that always runs. The throw statement raises an exception explicitly, while throws in a method signature declares that the method may propagate a checked exception.
Key points
- 1try marks code that might throw.
- 2catch handles a matching failure type.
- 3finally holds cleanup code that runs in almost all cases.
- 4throw raises an exception explicitly.
- 5throws declares propagated checked exceptions.
What is default exception handling?
Answer
If an exception is thrown and no application handler catches it, the JVM falls back to its default handler. That handler prints the exception name, message, and stack trace to the error output and terminates the thread where the failure occurred. If the terminated thread is the main thread and no non-daemon threads remain, the whole program ends.
💡 In interviews, stress the downside: default handling ends the thread, so production code should catch and handle expected failures.
Learn this topic
Recommended resourcesAffiliate links · may earn us a commission