Skip to content
Visual explainer 5h to learn 5 steps

Exceptions & generics

Write type-safe generic code and handle errors deliberately.

By Invicly Tech, , in Backend Java Development. About 11 minutes to read.

Topic 3 of 29

In short

Exceptions signal that something went wrong and let you handle it in one place. Generics let classes and methods work with any type while the compiler still checks type safety.

Explained simply

An exception is Java's way of saying something went wrong and the current method cannot continue normally. Instead of returning a strange value like -1, the method throws an exception object. It flies up through the callers until some code catches it and decides what to do.

Some exceptions are checked. The compiler forces you to either catch them or say throws in the method signature, because they describe things outside your control, like a missing file. Others are unchecked. They usually mean a bug, such as using a null reference, and the compiler does not force you to handle them.

Files, network connections and database connections must be closed after use. try-with-resources does this for you: you open the resource in the try header, and Java closes it at the end, even if an exception happens in the middle.

Generics let you write one class or method that works for many types while the compiler still checks them. A List<String> only accepts strings, so you never need risky casts. Bounds and wildcards, like <T extends Number>, let you say which types are allowed.

Press Play on a diagram to walk through it one step at a time.

MapException hierarchy
Throwable
  • Error (do not catch)
    • OutOfMemoryError
    • StackOverflowError
  • Exception (checked)
    • IOException
    • SQLException
    • Must catch or declare
  • RuntimeException (unchecked)
    • NullPointerException
    • IllegalArgumentException
    • IndexOutOfBoundsException
    • Subclass of Exception
FlowDeciding what to do with a caught exception
  1. Step 1
    Can you recover here?

    Yes: handle it, for example retry or use a default

  2. Step 2
    Can you add context?

    Yes: wrap it with a cause and a clearer message

  3. Step 3
    Otherwise let it go

    Do not catch it; declare or propagate

  4. Step 4
    Top-level handler

    One place logs it and returns an error

In depth

How an exception travels

When code throws, Java stops the current method and looks for a matching catch block in it. If there is none, the method ends and the exception moves to the caller, and so on up the call stack. This is called stack unwinding. If nothing catches it, the thread dies and the stack trace is printed. In a web app, the framework catches it at the top and returns an error response.

Catch blocks are checked from top to bottom, so put specific types before general ones; the compiler rejects a catch that can never be reached. A finally block runs whether or not an exception happened, which is why it was used for cleanup before try-with-resources. One catch can handle several unrelated types: catch (IOException | SQLException e).

FlowAn exception unwinding the call stack
  1. 1
    readConfig() throws

    IOException: file not found

  2. 2
    loadSettings() has no catch

    Its finally block runs, then it exits

  3. 3
    startApp() catches

    catch (IOException e) matches

  4. 4
    Handle

    Log it and use default settings

  5. 5
    Program continues

    Code after the catch runs normally

try-with-resources in detail

Any object that implements AutoCloseable can go in the try header. When the block ends, Java calls close() on each resource in reverse order of opening, so a statement is closed before its connection. If the body throws and close() also throws, the body's exception wins and the close failure is attached to it as a suppressed exception; you can read it with getSuppressed(). Old code with finally often lost the original error this way.

Since Java 9 you can also list an existing variable, as long as it is effectively final: try (conn) { ... }. You can still add catch and finally blocks; they run after the resources are closed.

  • Resources close in reverse order
  • Close failures become suppressed exceptions
  • Works with your own classes if they implement AutoCloseable

Designing your own exceptions

Create a custom exception when callers need to react to a specific problem, such as OrderNotFoundException or InsufficientFundsException. Extend RuntimeException for errors the caller usually cannot fix on the spot; most modern frameworks, including Spring, use unchecked exceptions for this reason. Use a checked exception only when every caller really should handle the case.

When you catch a low-level exception and throw your own, always pass the original as the cause: throw new ReportException("cannot build report", e). The stack trace then shows both, joined by Caused by. Throwing a new exception without the cause destroys the most useful debugging information. And never write an empty catch block; at minimum log the error or rethrow it.

  • Add a constructor (String message, Throwable cause)
  • Put useful data in the message: ids, values, limits
  • Do not use exceptions for normal control flow

Generics and type erasure

Generics are checked by the compiler and then mostly erased. At run time, List<String> and List<Integer> are the same class, java.util.List, and the compiler has inserted casts where you read values. This is called type erasure, and it explains several rules. You cannot write new T() or new T[10], because the type is unknown at run time. You cannot test obj instanceof List<String>. And a class cannot have two overloads that differ only by type argument.

Generic methods declare their own type parameter before the return type: static <T> T first(List<T> list). The compiler usually infers T from the arguments. Avoid raw types like plain List: they switch off the checks, and the mistake shows up later as a ClassCastException far from the real cause.

Bounds and wildcards: PECS

A bound limits a type parameter: <T extends Comparable<T>> means T must be comparable, so you may call compareTo. Wildcards use ? in a parameter type. The rule of thumb is PECS: Producer Extends, Consumer Super. If a method only reads items from a collection, accept List<? extends Number>, so a List<Integer> or List<Double> both work. If it only writes items into a collection, accept List<? super Integer>, so a List<Number> or List<Object> also works.

The JDK uses this everywhere. Collections.copy is declared as copy(List<? super T> dest, List<? extends T> src). Note that List<Integer> is not a subtype of List<Number>, even though Integer is a Number. Wildcards are how you get that flexibility back safely.

Compare? extends vs ? super
List<? extends Number>
  • Producer: you read from it
  • Accepts List<Integer>, List<Double>
  • get() returns a Number
  • add() is not allowed (except null)
List<? super Integer>
  • Consumer: you write into it
  • Accepts List<Integer>, List<Number>, List<Object>
  • add(5) is allowed
  • get() only gives Object

Learn it in 5 short steps

About 1h each. Track them with a timer in your plan.

  1. 1
    Compare checked and unchecked exceptions~1h
  2. 2
    Close resources with try-with-resources~1h
  3. 3
    Create custom exception types~1h
  4. 4
    Write generic classes and methods~1h
  5. 5
    Use bounded types and wildcards~1h

Key points

  • Checked exceptions must be caught or declared with throws; unchecked ones need not be.
  • RuntimeException extends Exception, but the compiler does not force you to handle it.
  • try-with-resources closes files and connections automatically, even when an exception occurs.
  • Bounded generics like <T extends Comparable<T>> let you call methods of the bound safely.

Key terms

Tap a card to flip it. 0/5 known

Examples

java
class NotFoundException extends RuntimeException {
  NotFoundException(String msg) { super(msg); }
}

static <T extends Comparable<T>> T max(List<T> list) {
  if (list.isEmpty()) throw new NotFoundException("empty list");
  T best = list.get(0);
  for (T x : list) if (x.compareTo(best) > 0) best = x;
  return best;
}
try (var reader = Files.newBufferedReader(Path.of("data.txt"))) {
  System.out.println(reader.readLine());
} catch (IOException e) {
  System.err.println("Could not read: " + e.getMessage());
}

A custom unchecked exception, a bounded generic method and auto-closing a reader.

Wrapping a low-level error with context

A service reads a price list from disk. Step 1: the file call throws a checked IOException. Step 2: the service cannot fix a missing file, so it wraps the error in its own unchecked PriceListException and passes the cause. Step 3: the message names the file, so the log line is useful on its own. Step 4: callers do not need throws clauses, and the stack trace still shows Caused by: java.nio.file.NoSuchFileException.

java
class PriceListException extends RuntimeException {
  PriceListException(String msg, Throwable cause) { super(msg, cause); }
}

List<String> loadPrices(Path file) {
  try {
    return Files.readAllLines(file);
  } catch (IOException e) {
    throw new PriceListException("cannot read price list " + file, e);
  }
}

A generic method that sums any numbers

You want one sum method for List<Integer>, List<Long> and List<Double>. Step 1: List<Number> will not accept a List<Integer>, because generic types are not covariant. Step 2: the method only reads, so it is a producer: use List<? extends Number>. Step 3: call doubleValue(), which every Number has. Step 4: the same method now works for all three lists without casts.

java
static double sum(List<? extends Number> nums) {
  double total = 0;
  for (Number n : nums) total += n.doubleValue();
  return total;
}

sum(List.of(1, 2, 3));        // 6.0
sum(List.of(1.5, 2.5));       // 4.0
sum(List.of(10L, 20L));       // 30.0

Quick reference

  • Checked: catch it or declare throws. Unchecked (RuntimeException): optional
  • Catch specific exceptions before general ones
  • Always pass the cause when wrapping: new MyException(msg, e)
  • try-with-resources closes in reverse order and keeps close errors as suppressed
  • Never leave a catch block empty
  • PECS: Producer extends (read), Consumer super (write)
  • List<Integer> is not a List<Number>; use List<? extends Number>
  • Type erasure: no new T(), no instanceof List<String>

Common mistakes

  • Catching Exception and ignoring it, which hides real bugs.
  • Using raw types like List instead of List<String>, losing type checks.
  • Forgetting to close resources when not using try-with-resources.

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1In try-with-resources, the body throws an exception and close() also throws. What does the caller receive?

Question 2

2Why can you not write new T() inside a generic class?

Question 3

3A method should add Integers into a list given by the caller. Which parameter type is most flexible?

Question 4

4What is the main problem with catch (Exception e) {} in business code?

0/4 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    Write a method parseAge(String s) that returns the age as an int and throws IllegalArgumentException with a clear message if s is not a number or is negative.

  2. Exercise 2medium

    Write a class Timer that implements AutoCloseable and prints how many milliseconds passed between its creation and close(). Use it in try-with-resources around some work.

  3. Exercise 3hard

    Write a generic method static <T extends Comparable<? super T>> T maxOf(Collection<? extends T> items) that throws NoSuchElementException on an empty collection.

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

Should I use checked or unchecked exceptions?
Use unchecked exceptions for most application errors; that is what Spring and most modern libraries do. Use checked ones only when every caller can and should recover, such as a parser that reports bad input.
Should I ever catch Throwable or Error?
Almost never. Errors like OutOfMemoryError mean the JVM is in trouble, and trying to continue usually makes things worse. A top-level handler may log them before the process exits.
What does "unchecked cast" warning mean?
You cast to a generic type that the JVM cannot verify at run time because of type erasure. The code may fail later with ClassCastException, so fix the types instead of suppressing the warning where possible.
Is it slow to throw exceptions?
Creating an exception fills in a stack trace, which costs time, so do not use exceptions for normal control flow in hot loops. For real error cases the cost does not matter.

Go deeper

ShareXLinkedInWhatsApp