Skip to content
Java Exceptions & Generics Interview Deep Dive: Type Erasure, PECS, try-with-resources
Fundamentals 23 min read

Java Exceptions & Generics Interview Deep Dive: Type Erasure, PECS, try-with-resources

This article covers Java exception hierarchy, checked vs unchecked exceptions, try-with-resources best practices, custom exception design, and generics type erasure with bridge methods, wildcard bounds, and the PECS principle for interview preparation.

Rain's Path to Java Mastery
Rain's Path to Java Mastery
Rain's Path to Java Mastery

Java Exception System

All exceptions inherit from java.lang.Throwable, which splits into two branches:

java.lang.Throwable
├─ java.lang.Error ❌ (system-level errors, unrecoverable)
└─ java.lang.Exception ⚠️ (program-level exceptions, handleable)
   ├─ java.lang.RuntimeException 🚀 (unchecked / runtime exceptions)
   └─ other Exception subclasses 📋 (checked / compile-time exceptions)

Core rule:

Subclasses of RuntimeException or Error → unchecked exceptions (unchecked).

Subclasses of Exception but not RuntimeException → checked exceptions (checked).

Error (Errors)

JVM-level severe problems; programs cannot handle them and should never catch them.

Common examples: OutOfMemoryError (OOM), StackOverflowError, NoClassDefFoundError.

Interview point: Error is not an Exception; catch(Exception e) cannot catch Error.

Exception (Exceptions)

Divided into checked and unchecked exceptions — a must-know interview topic.

Checked vs Unchecked Exception Comparison

Compile-time check: Checked — mandatory (compile fails if unhandled); Unchecked — no check.

Inheritance: Checked — directly extend Exception (excluding RuntimeException); Unchecked — extend RuntimeException.

Handling: Checked — must try-catch or declare throws; Unchecked — optional, recommended not to catch.

Occurrence: Checked — predictable external failures (file missing, network down); Unchecked — runtime logic bugs (null pointer, index out of bounds).

Design intent: Checked — force handling of foreseeable external risks; Unchecked — expose bugs for fixing.

Examples: Checked — IOException, SQLException, FileNotFoundException; Unchecked — NullPointerException, ArrayIndexOutOfBoundsException, ClassCastException.

Interview Tips & Pitfalls

Never catch Throwable — it swallows Error, hiding system crashes.

Never swallow exceptions silently — at minimum log them.

Prefer unchecked exceptions (Effective Java Item 71) to avoid polluting call chains.

Overuse of checked exceptions bloats code; Spring, MyBatis, etc., have largely switched to unchecked.

Custom exception selection:

External dependency failures (e.g., third-party API) → checked exception.

Program logic errors (invalid args, illegal state) → unchecked exception.

Memory mnemonics:

🧬 Error = JVM critical illness, don't self-medicate.

📦 Checked = external dependency misbehaves, must give an account.

🐞 Unchecked = own code bug, fix it fast.

Exception Handling Mechanism & Custom Exception Design

Core Mechanism

Exception inheritance tree (reiterated):

Throwable
├─ Error (unrecoverable)
│  ├─ OutOfMemoryError
│  ├─ StackOverflowError
│  └─ VirtualMachineError
└─ Exception (handleable)
   ├─ RuntimeException (unchecked)
   │  ├─ NullPointerException
   │  ├─ IndexOutOfBoundsException
   │  ├─ ClassCastException
   │  └─ IllegalArgumentException
   └─ Checked Exceptions
      ├─ IOException
      ├─ SQLException
      └─ InterruptedException
Exception hierarchy diagram
Exception hierarchy diagram

Execution Flow

Normal flow: try → execute all code → finally → subsequent code
Exception flow: try → exception occurs → match catch → execute catch → finally → subsequent code
Uncaught exception: try → exception occurs → no matching catch → finally → method exits → propagates upward

Key Points

finally

block always executes (unless System.exit(0) or JVM crash).

Modifying return value in finally overrides the return from try / catch. try-with-resources (Java 7+) auto-closes resources implementing AutoCloseable, superior to traditional finally.

// Recommended ✅
try (InputStream is = new FileInputStream("test.txt")) {
    // business code
} catch (IOException e) {
    // exception handling
}
// No manual close needed; JVM auto-invokes close()

Exception Propagation

Exceptions propagate up the call stack until caught or reach main.

Uncaught exceptions terminate the current thread.

Global handler via Thread.setUncaughtExceptionHandler().

Custom Exception Best Practices

Why Custom Exceptions?

Clear business semantics: distinguish system vs business exceptions (e.g., UserNotFoundException vs NullPointerException).

Unified handling: global handlers can treat custom exceptions specially.

Carry extra info: error codes, descriptions, request IDs.

Faster diagnosis: module-specific exceptions pinpoint source.

Design Principles

Choose correct parent:

Business exception → extend RuntimeException (unchecked).

Must-force-external-handling → extend Exception (checked, rarely used).

Provide multiple constructors:

public class BusinessException extends RuntimeException {
    private String code; // error code

    public BusinessException(String message) {
        super(message);
    }

    public BusinessException(String code, String message) {
        super(message);
        this.code = code;
    }

    public BusinessException(String message, Throwable cause) {
        super(message, cause);
    }
}

Preserve full exception chain: wrap original exception as cause to retain stack trace.

Moderate granularity: not one per module, not one per method.

Unified error code system: each exception maps to a unique code for frontend handling.

Common Design Mistakes

Swallowing exceptions: catch without logging or rethrowing.

// Wrong ❌
try {
    // business code
} catch (Exception e) {
    // do nothing
}

Imprecise exception types: catching Exception or even Throwable.

Throwing in finally : masks original exception.

Incomplete error info: only printing "error occurred" without context.

Frequent Interview Q&A

Q: Difference between throw and throws ?

A: throw actively throws an exception object; throws declares exception types a method may throw.

Q: NoClassDefFoundError vs ClassNotFoundException ?

A: ClassNotFoundException is checked, occurs when class loader cannot find a class at load time; NoClassDefFoundError is an Error, occurs when class existed at compile time but missing at runtime.

Q: Performance impact of exception handling?

A: Creating exception objects generates stack traces — costly; don't use exceptions for normal control flow.

Q: Unified exception handling in Spring Boot?

A: Use @RestControllerAdvice + @ExceptionHandler to globally catch and process exceptions.

Generics: Type Erasure, Wildcards ? extends / ? super

Opening Answer

These two points are the core underlying logic and practical boundaries of Java generics. Covered in four parts: why erasure, what erasure does, erasure pitfalls, how wildcards compensate.

Core Concepts

Type Erasure

Interviewer: Can this compile?

List<String> list = new ArrayList<>();
list.add("hello");
// Can we get String type at runtime?

You: At runtime String is unavailable; generic info erased, list is just raw ArrayList in bytecode.

Interviewer ✅: Exactly — "generics erasure". One-liner: Compiler wears clothes, runtime runs naked 🩳.

Why erasure? To maintain compatibility with pre-JDK 1.5 non-generic code (e.g., raw ArrayList storing Object). Java chose compile-time checking + runtime erasure.

What erasure does (with comparison):

Compile-time (with generics) → Runtime (erased): ArrayList<String> → ArrayList (raw type) T get(int index) →

Object get(int index)
void add(T e)

→ void add(Object e) Boundary erasure rules:

Unbounded generic → erased to Object.

Bounded generic ( T extends Number) → erased to first bound Number.

Example:

public class Box<T> {
    private T data;
    public T getData() { return data; }
}
// After erasure
public class Box {
    private Object data; // T replaced by Object
    public Object getData() { return data; }
}

If <T extends Comparable<T>>, T erases to Comparable.

Three Classic Erasure Pitfalls:

Cannot use primitives as generics: erased to Object which cannot hold int; must use wrapper Integer.

Cannot instanceof parameterized types: if (obj instanceof ArrayList<String>) compile error.

Static fields/methods cannot use class type parameters: class generics are instance-level; static members belong to class.

Two Erasure "Easter Eggs":

Bridge Methods — inserted by compiler to preserve overriding polymorphism. Example:

class Node<T> {
    public void setData(T data) { ... }
}
class MyNode extends Node<Integer> {
    public void setData(Integer data) { ... }
}
// After erasure Node has setData(Object); for polymorphism compiler generates bridge:
// public void setData(Object data) { setData((Integer) data); }

Cannot directly create generic arrays: new T[10] illegal because erasure yields Object[]; casting to (T[]) breaks type safety. Workaround via reflection: (T[]) Array.newInstance(clazz, size).

Bonus: Generic info not entirely lost — List<String> and List<Integer> share same Class object, but field/method generic signatures remain in bytecode Signature attribute, accessible via reflection.

Wildcards ? extends / ? super

Scenario: method reads and writes a collection of fruits.

List<Apple> apples = new ArrayList<>();
// Want a parameter accepting both List<Apple> and List<Fruit>?

Use List<? extends Fruit> to accept any Fruit subtype list, but cannot add elements; use List<? super Fruit> to add Fruit and subtypes, but read only as Object.

Interviewer 👍: You've touched the PECS principle.

? extends — Upper Bound (Read-Only Model)

List<? extends Fruit> fruits = new ArrayList<Apple>(); // legal
fruits.add(new Apple()); // ❌ compile error!
Fruit f = fruits.get(0); // ✅ can read, returns Fruit

Reason: unknown whether the list holds Apple or Orange; adding Apple could corrupt List<Orange>. Compiler forbids add (except null). Thus it's a Producer (provides data) — PECS P (Producer Extends).

? super — Lower Bound (Write-Only Model)

List<? super Fruit> basket = new ArrayList<Object>();
basket.add(new Apple()); // ✅ can add Fruit and subtypes
basket.add(new Fruit());
Object obj = basket.get(0); // ⚠️ read only as Object
? super Fruit

sets lower bound to Fruit, so adding Fruit or subtypes is safe (upcast). Reading yields only Object (upper bound is Object). Thus it's a Consumer (consumes data) — PECS C (Consumer Super).

Wildcard covariance/contravariance diagram
Wildcard covariance/contravariance diagram

Supermarket basket analogy:

Object
         ↑
        Fruit
         ↑   ↑
      Apple Orange

? extends Fruit → basket "contains" some Fruit subtype (uncertain), only take out, cannot put in.
? super Fruit  → basket "accepts" Fruit and above (Object), can put Fruit/subtypes, but take out only as Object.

Why Wildcards?

Solve "generics lack covariance/contravariance" (e.g., ArrayList<String> cannot assign to ArrayList<Object> despite String being Object subtype).

PECS Principle (Must Memorize)

PECS: Producer Extends (use ? extends, read-only), Consumer Super (use ? super, write-only). ? extends T: upper bound, represents "T or any subtype of T"; covariant ( ArrayList<Apple> → ArrayList<? extends Fruit> legal); can read (auto-cast to T); cannot write (except null); analogy: fruit basket lid — only view/take fruit, cannot randomly insert (fear putting orange into apple basket). ? super T: lower bound, represents "T or any supertype of T"; contravariant ( ArrayList<Fruit> → ArrayList<? super Apple> legal); read only as Object; can write (T or subtypes); analogy: garbage disposal inlet — only put apple/fuji apple (T=Apple), but retrieved items treated as garbage (Object).

Classic Use Cases

Producer Extends:

Collections.copy(List<? super T> dest, List<? extends T> src)

→ src produces data.

Consumer Super: Stream.forEach(Consumer<? super T> action) → action consumes data.

Closing Bonus Points

If you need both read and write, don't use wildcards; use a generic method (e.g., <T> void copy(List<T> dest, List<T> src)).

"Can List&lt;String&gt; be passed to List&lt;Object&gt; parameter?" No. Generics are invariant; List<String> is not a subtype of List<Object>. Covariance only via wildcard List<? extends Object>.

"When to use &lt;T&gt; vs &lt;?&gt; ?"

Method doesn't care about concrete type and only reads → use <? extends X> or <? super X> for flexibility.

Need type dependency across parameters (e.g., return type matches parameter type) → use generic method <T>.

// Type dependency: two params must be same type
public static <T> void swap(List<T> list, int i, int j);

Summary Mnemonics

Generics erasure remembers upper bound; bridge methods preserve polymorphism.

Upper bound extends read-only; lower bound super write-only, read as Object.

PECS: Producer Extends, Consumer Super.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

JavaGenericsinterview preparationtry-with-resourcesPECSType ErasureExceptionsChecked vs Unchecked
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.