Java Exception Architecture, Keywords, Handling, and Common Interview Questions
This article provides a comprehensive overview of Java's exception hierarchy, key keywords, handling techniques, common interview questions, and best‑practice guidelines, illustrating concepts with numerous code examples to help developers write robust and maintainable backend code.
Java Exception Architecture and Keywords
Java provides a unified mechanism for recognizing and responding to errors, separating error‑handling code from normal business logic to improve readability and robustness.
Exception Overview
Exceptions answer the three questions: what (exception type), where (stack trace), and why (message).
Exception Hierarchy
1. Throwable
Throwable is the superclass of all errors and exceptions. It has two direct subclasses: Error and Exception.
2. Error
Errors represent serious problems that the application should not try to catch, such as OutOfMemoryError or StackOverflowError.
3. Exception
Exceptions can be caught and handled. They are divided into checked (compile‑time) and unchecked (runtime) exceptions.
3.1 RuntimeException (unchecked)
RuntimeException and its subclasses are not checked by the compiler. Examples include NullPointerException, ArrayIndexOutOfBoundsException, ClassCastException, ArithmeticException.
3.2 Checked Exception
Checked exceptions (e.g., IOException, ClassNotFoundException) must be declared or caught, otherwise the code will not compile.
4. Checked vs Unchecked
Checked exceptions require explicit handling; unchecked exceptions indicate programming errors and may be optionally caught.
Key Keywords
try – encloses code that may throw an exception.
catch – handles the thrown exception.
finally – always executes for resource cleanup.
throw – throws an exception object.
throws – declares exceptions a method may propagate.
Exception Handling in Java
Java uses five keywords (try, catch, finally, throw, throws) to manage exceptions. The JVM creates an exception object, walks the call stack to find a matching handler, or delegates to the default handler.
Declaring Exceptions
Use throws in a method signature to propagate checked exceptions; non‑checked exceptions need not be declared.
Catching Exceptions
Wrap risky code in try and handle specific exceptions in catch blocks.
Choosing Exception Types
Prefer the most specific exception type; place generic catches last.
Common Patterns
Direct Throw
private static void readFile(String filePath) throws IOException {
File file = new File(filePath);
String result;
BufferedReader reader = new BufferedReader(new FileReader(file));
while ((result = reader.readLine()) != null) {
System.out.println(result);
}
reader.close();
}Wrap and Re‑throw
private static void readFile(String filePath) throws MyException {
try {
// code
} catch (IOException e) {
MyException ex = new MyException("read file failed.");
ex.initCause(e);
throw ex;
}
}Multiple Catch
private static void readFile(String filePath) {
try {
// code
} catch (FileNotFoundException e) {
// handle
} catch (IOException e) {
// handle
}
}Multi‑catch
private static void readFile(String filePath) {
try {
// code
} catch (FileNotFoundException | UnknownHostException e) {
// handle both
} catch (IOException e) {
// handle
}
}Custom Exception Class
public class MyException extends Exception {
public MyException() {}
public MyException(String msg) { super(msg); }
// ...
}try‑catch‑finally
private static void readFile(String filePath) throws MyException {
File file = new File(filePath);
String result;
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(file));
while ((result = reader.readLine()) != null) {
System.out.println(result);
}
} catch (IOException e) {
System.out.println("readFile method catch block.");
MyException ex = new MyException("read file failed.");
ex.initCause(e);
throw ex;
} finally {
System.out.println("readFile method finally block.");
if (reader != null) {
try { reader.close(); } catch (IOException e) { e.printStackTrace(); }
}
}
}try‑with‑resources (Java 7+)
public void automaticallyCloseResource() {
File file = new File("./tmp.txt");
try (FileInputStream inputStream = new FileInputStream(file)) {
// use inputStream
} catch (FileNotFoundException e) {
log.error(e);
} catch (IOException e) {
log.error(e);
}
}Common Interview Questions
Difference between Error and Exception.
Runtime vs checked exceptions.
How the JVM processes an exception.
Difference between throw and throws.
Differences among final, finally, finalize.
NoClassDefFoundError vs ClassNotFoundException.
Which parts of try‑catch‑finally can be omitted.
Will finally execute if catch returns?
Typical RuntimeException examples.
Common Java exceptions list.
Best Practices (Alibaba Java Development Manual)
Do not catch unchecked exceptions such as NullPointerException for flow control.
Avoid using exceptions for normal program logic.
Separate stable and unstable code; catch specific exceptions for unstable code.
Never swallow an exception without handling or re‑throwing.
Always close resources in finally or use try‑with‑resources.
Do not return from finally; it overrides earlier returns.
Catch the most specific exception first, then generic ones.
Avoid catching Throwable unless absolutely necessary.
Prefer standard exceptions; create custom ones only when needed.
Document thrown exceptions with @throws in Javadoc.
These guidelines help write clear, maintainable Java code and prepare for interview questions on exception handling.
Selected Java Interview Questions
A professional Java tech channel sharing common knowledge to help developers fill gaps. Follow us!
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.