Design a good exception class
35 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)A good exception class tells the catcher exactly what went wrong, with the data needed to act on it. A few design habits make that happen: one family of exceptions per application, useful fields, constructors that keep the cause, and stable error codes.
One base exception for an application
A base exception is one class at the top of your application's own exceptions, such as FeeAppException. Every specific exception (StudentNotFoundException, PaymentTooLargeException) extends it.
Example 1 · A base exception with two children
import java.util.HashMap;import java.util.Map;
class FeeAppException extends RuntimeException { FeeAppException(String message) { super(message); }}
class StudentNotFoundException extends FeeAppException { StudentNotFoundException(String roll) { super("No student with roll " + roll); }}
class PaymentTooLargeException extends FeeAppException { PaymentTooLargeException(int amount, int due) { super("Paid Rs " + amount + " but only Rs " + due + " is due"); }}
public class BaseExceptionDemo { static Map<String, Integer> due = new HashMap<>();
static void pay(String roll, int amount) { Integer d = due.get(roll); if (d == null) { throw new StudentNotFoundException(roll); } if (amount > d) { throw new PaymentTooLargeException(amount, d); } due.put(roll, d - amount); System.out.println(roll + " paid Rs " + amount + ", still due Rs " + (d - amount)); }
public static void main(String[] args) { due.put("101", 25000); String[] rolls = {"101", "999", "101"}; int[] amounts = {20000, 5000, 9000}; for (int i = 0; i < rolls.length; i++) { try { pay(rolls[i], amounts[i]); } catch (FeeAppException e) { System.out.println(e.getClass().getSimpleName() + ": " + e.getMessage()); } } }}101 paid Rs 20000, still due Rs 5000 StudentNotFoundException: No student with roll 999 PaymentTooLargeException: Paid Rs 9000 but only Rs 5000 is due
What this code does
- One
catch (FeeAppException e)handles both children, because a catch block also catches every subclass of its type. - A
NullPointerExceptionfrom a bug would not be caught here, since it is not aFeeAppException. Known problems and bugs stay apart.
The base class lets the top of the program catch "any known problem in our app" with one catch, while bugs such as NullPointerException still stand out because they are not part of that family. Its name also tells a reader at once where an error came from. Keep the tree shallow: one base class and a handful of children. Add a new child only when some caller needs to catch that case on its own.
Extra fields: error code, line number, value
An exception is an ordinary class, so it can carry fields: the line number of a bad row, the value that was wrong, an error code. Make them private final, set them in the constructor and add getters.
Example 2 · Fields: line number and bad value
import java.util.ArrayList;import java.util.List;
class MarksFormatException extends RuntimeException { private final int lineNumber; private final String value;
MarksFormatException(int lineNumber, String value, String problem) { super("Line " + lineNumber + ": " + problem + " (value: '" + value + "')"); this.lineNumber = lineNumber; this.value = value; }
int lineNumber() { return lineNumber; } String value() { return value; }}
public class FieldsDemo { static boolean isDigits(String s) { return !s.isEmpty() && s.chars().allMatch(Character::isDigit); }
static int parseMarks(int lineNumber, String line) { String[] parts = line.split(","); if (parts.length != 2) { throw new MarksFormatException(lineNumber, line, "expected roll,marks"); } String text = parts[1].trim(); if (!isDigits(text)) { throw new MarksFormatException(lineNumber, text, "marks is not a number"); } int marks = Integer.parseInt(text); if (marks > 100) { throw new MarksFormatException(lineNumber, text, "marks above 100"); } return marks; }
public static void main(String[] args) { List<String> lines = List.of("101,78", "102,abc", "103", "104,105", "105,64"); List<Integer> badLines = new ArrayList<>(); int total = 0; for (int i = 0; i < lines.size(); i++) { try { total += parseMarks(i + 1, lines.get(i)); } catch (MarksFormatException e) { System.out.println(e.getMessage()); badLines.add(e.lineNumber()); } } System.out.println("Total of good rows: " + total); System.out.println("Fix these lines: " + badLines); }}Line 2: marks is not a number (value: 'abc') Line 3: expected roll,marks (value: '103') Line 4: marks above 100 (value: '105') Total of good rows: 142 Fix these lines: [2, 3, 4]
What this code does
- The exception keeps the line number and the bad value as
private finalfields, and builds its message from the same data. maincollectse.lineNumber()into a list without touching the message text. Changing the wording of the message later cannot break this code.
Fields let code act on the error without cutting the message apart with substring. A file importer can collect the bad line numbers into a list, and a screen can highlight the exact field that was wrong. Build the message from the same data in the constructor, so the message and the fields always agree.
Constructors with message and cause
The cause is the lower-level exception that led to yours, such as the NumberFormatException behind "fee amount is not a number". Exception and RuntimeException both have a constructor (String message, Throwable cause) that stores it.
Example 3 · Two constructors: message, and message with cause
class FeeAppException extends RuntimeException { FeeAppException(String message) { super(message); }
FeeAppException(String message, Throwable cause) { super(message, cause); }}
public class CauseDemo { static int parseAmount(String text) { try { return Integer.parseInt(text.trim()); } catch (NumberFormatException e) { throw new FeeAppException("Fee amount is not a whole number: '" + text + "'", e); } }
public static void main(String[] args) { System.out.println(parseAmount(" 45000 ")); try { parseAmount("45,000"); } catch (FeeAppException e) { System.out.println(e.getMessage()); Throwable cause = e.getCause(); System.out.println("Cause: " + cause.getClass().getSimpleName() + ": " + cause.getMessage()); } }}45000 Fee amount is not a whole number: '45,000' Cause: NumberFormatException: For input string: "45,000"
What this code does
- The second constructor passes
causetosuper(message, cause), sogetCause()returns the originalNumberFormatException. - If this exception reached the top uncaught, its stack trace would show
FeeAppExceptionfirst and then aCaused by: java.lang.NumberFormatExceptionsection with the original line.
Give your class at least two constructors: (String message) and (String message, Throwable cause), each passing its arguments to super. Then getCause() returns the original exception, and a stack trace shows it under Caused by:. A class with only a message constructor forces callers to throw the original error away.
An enum of error codes
An error code is a short, stable id for a kind of problem, such as E102 for "fee already paid". Put the codes in an enum, and give one exception class a field of that enum type.
Example 4 · One exception class with an enum of codes
import java.util.HashSet;import java.util.Map;import java.util.Set;
enum ErrorCode { STUDENT_NOT_FOUND("E101", "Student not found"), FEE_ALREADY_PAID("E102", "Fee already paid"), AMOUNT_MISMATCH("E103", "Amount does not match the fee");
private final String code; private final String text;
ErrorCode(String code, String text) { this.code = code; this.text = text; }
String code() { return code; } String text() { return text; }}
class FeeException extends RuntimeException { private final ErrorCode errorCode;
FeeException(ErrorCode errorCode, String detail) { super(errorCode.code() + " " + errorCode.text() + ": " + detail); this.errorCode = errorCode; }
ErrorCode errorCode() { return errorCode; }}
public class ErrorCodeDemo { static Map<String, Integer> fees = Map.of("101", 45000, "102", 45000); static Set<String> paid = new HashSet<>(Set.of("102"));
static void pay(String roll, int amount) { Integer fee = fees.get(roll); if (fee == null) { throw new FeeException(ErrorCode.STUDENT_NOT_FOUND, "roll " + roll); } if (paid.contains(roll)) { throw new FeeException(ErrorCode.FEE_ALREADY_PAID, "roll " + roll); } if (amount != fee) { throw new FeeException(ErrorCode.AMOUNT_MISMATCH, "expected " + fee + ", got " + amount); } paid.add(roll); System.out.println("Fee paid for roll " + roll); }
static String advice(ErrorCode code) { return switch (code) { case STUDENT_NOT_FOUND -> "Check the roll number on your ID card."; case FEE_ALREADY_PAID -> "Download the receipt from the portal."; case AMOUNT_MISMATCH -> "Pay the exact amount shown on the fee slip."; }; }
public static void main(String[] args) { String[] rolls = {"101", "101", "102", "777"}; int[] amounts = {40000, 45000, 45000, 45000}; for (int i = 0; i < rolls.length; i++) { try { pay(rolls[i], amounts[i]); } catch (FeeException e) { System.out.println(e.getMessage()); System.out.println(" -> " + advice(e.errorCode())); } } }}E103 Amount does not match the fee: expected 45000, got 40000 -> Pay the exact amount shown on the fee slip. Fee paid for roll 101 E102 Fee already paid: roll 102 -> Download the receipt from the portal. E101 Student not found: roll 777 -> Check the roll number on your ID card.
What this code does
- Three kinds of problem share one class,
FeeException; theerrorCodefield says which kind it is. - The
switchone.errorCode()picks the advice. Because it is a switch expression over an enum, the compiler complains if a new code is added and not handled.
This replaces twenty tiny classes with one class plus a list of codes. A switch on the code picks the advice to show, support staff can search for E102 in the logs, and the code stays the same even when someone rewords the message. Use subclasses when callers must catch the cases differently; use codes when they are handled the same way but reported differently.
A good exception class: the checklist
Most well-designed exception classes look alike. Run through this list before you add one.
- The name ends in
Exceptionand says what went wrong:SeatUnavailableException, notBookingError2. - It extends your base exception (or
Exceptionif it must be checked, as the previous lesson explains). - It has
(message)and(message, cause)constructors, plus any data fields asprivate finalwith getters. - The message names the bad value:
Line 4: marks above 100 (value: '105'), not justInvalid input.
Next step
Check your understanding
12 quick questions