Translate exceptions at layer boundaries
35 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)Each layer of an app should report errors in its own words. The storage layer turns an IOException into a StorageException that says what the app was doing, keeps the original as its cause, and leaves file paths out of anything the user will see.
Layers: storage, service and user interface
A layer is a group of classes with one job. A small app usually has three: storage (reads and writes files or a database), service (rules and calculations) and user interface (UI, talks to the user).
Example 1 · Three layers, and an IOException that leaks upward
import java.io.IOException;import java.nio.file.Files;import java.nio.file.Path;import java.util.ArrayList;import java.util.List;
class MarksStorage { // storage layer: files only private final Path folder;
MarksStorage(Path folder) { this.folder = folder; }
List<Integer> load(String className) throws IOException { List<Integer> marks = new ArrayList<>(); for (String line : Files.readAllLines(folder.resolve(className + ".csv"))) { marks.add(Integer.parseInt(line.split(",")[1].trim())); } return marks; }}
class ReportService { // service layer: rules and numbers private final MarksStorage storage;
ReportService(MarksStorage storage) { this.storage = storage; }
// Only calculates an average, yet must mention IOException String summary(String className) throws IOException { List<Integer> marks = storage.load(className); int total = 0; for (int m : marks) { total += m; } return className + ": " + marks.size() + " students, average " + total / marks.size(); }}
public class LayersDemo { public static void main(String[] args) throws IOException { Path folder = Files.createTempDirectory("marks"); Path file = folder.resolve("10A.csv"); Files.write(file, List.of("101,78", "102,91", "103,66"));
ReportService service = new ReportService(new MarksStorage(folder)); System.out.println(service.summary("10A"));
Files.delete(file); Files.delete(folder); }}10A: 3 students, average 78
What this code does
- Each class has one job:
MarksStoragereads the file,ReportServicecalculates, andmainplays the UI and prints. ReportService.summaryonly adds numbers, but becauseloaddeclaresthrows IOException, so mustsummary, and so mustmain. A file detail has leaked through every layer.
Each layer should speak its own language. The storage layer knows about paths and IOException. The service layer knows about classes, marks and averages. The UI knows about screens and messages.
When a storage method declares throws IOException, that file detail leaks upward: the service must declare it too, and soon every method mentions files, even ones that only calculate an average.
IOException becomes a StorageException
Exception translation means catching a low-level exception at a layer boundary and throwing a new one that fits the layer above, with the original kept as its cause.
Exception translation means catching a low-level exception at a layer boundary and throwing a new one that fits the layer above. The storage layer catches IOException and throws a StorageException with a message in the app's own words: Could not load marks for class 10B.
Example 2 · Translate at the storage boundary
import java.io.IOException;import java.nio.file.Files;import java.nio.file.Path;import java.util.ArrayList;import java.util.List;
class StorageException extends RuntimeException { StorageException(String message, Throwable cause) { super(message, cause); }}
class MarksStorage { private final Path folder;
MarksStorage(Path folder) { this.folder = folder; }
List<Integer> load(String className) { try { List<Integer> marks = new ArrayList<>(); for (String line : Files.readAllLines(folder.resolve(className + ".csv"))) { marks.add(Integer.parseInt(line.split(",")[1].trim())); } return marks; } catch (IOException e) { throw new StorageException("Could not load marks for class " + className, e); } }}
class ReportService { private final MarksStorage storage;
ReportService(MarksStorage storage) { this.storage = storage; }
String summary(String className) { // no more "throws IOException" List<Integer> marks = storage.load(className); int total = 0; for (int m : marks) { total += m; } return className + ": " + marks.size() + " students, average " + total / marks.size(); }}
public class TranslateDemo { public static void main(String[] args) throws IOException { Path folder = Files.createTempDirectory("marks"); Path file = folder.resolve("10A.csv"); Files.write(file, List.of("101,78", "102,91", "103,66")); ReportService service = new ReportService(new MarksStorage(folder));
for (String cls : List.of("10A", "10B")) { try { System.out.println(service.summary(cls)); } catch (StorageException e) { System.out.println("Storage problem: " + e.getMessage()); System.out.println("Cause type: " + e.getCause().getClass().getSimpleName()); } }
Files.delete(file); Files.delete(folder); }}10A: 3 students, average 78 Storage problem: Could not load marks for class 10B Cause type: NoSuchFileException
What this code does
MarksStorage.loadcatchesIOExceptionat its own edge and throwsStorageException, an unchecked exception with a message about classes and marks, not files.ReportService.summarylost itsthrows IOException. The missing10B.csvstill reachesmain, but as an app exception whose cause is the originalNoSuchFileException.
Now the service and UI layers never see IOException, and their method headers lose throws IOException. If the storage later moves from CSV files to a database, they do not change at all: only the storage layer knows what it reads from.
Keeping the cause
A translated exception must carry the original one as its cause: throw new StorageException("Could not load marks for class " + cls, e);. The new message explains what the app was doing; the cause explains what actually broke.
Example 3 · Without the cause, two different failures look the same
import java.io.IOException;import java.nio.file.Files;import java.nio.file.Path;import java.util.ArrayList;import java.util.List;
class StorageException extends RuntimeException { StorageException(String message) { super(message); } StorageException(String message, Throwable cause) { super(message, cause); }}
class MarksStorage { private final Path folder; private final boolean keepCause;
MarksStorage(Path folder, boolean keepCause) { this.folder = folder; this.keepCause = keepCause; }
List<Integer> load(String className) { try { List<Integer> marks = new ArrayList<>(); for (String line : Files.readAllLines(folder.resolve(className + ".csv"))) { marks.add(Integer.parseInt(line.split(",")[1].trim())); } return marks; } catch (IOException | NumberFormatException e) { String msg = "Could not load marks for class " + className; throw keepCause ? new StorageException(msg, e) : new StorageException(msg); } }}
public class KeepCauseDemo { static String chain(Throwable t) { StringBuilder sb = new StringBuilder(t.getClass().getSimpleName()); for (Throwable c = t.getCause(); c != null; c = c.getCause()) { sb.append(" <- ").append(c.getClass().getSimpleName()); } return sb.toString(); }
public static void main(String[] args) throws IOException { Path folder = Files.createTempDirectory("marks"); Path bad = folder.resolve("10C.csv"); Files.write(bad, List.of("101,78", "102,ab")); // 10B.csv is missing
for (boolean keep : new boolean[]{false, true}) { System.out.println(keep ? "With cause:" : "Without cause:"); MarksStorage storage = new MarksStorage(folder, keep); for (String cls : List.of("10B", "10C")) { try { storage.load(cls); } catch (StorageException e) { System.out.println(" " + cls + ": " + chain(e)); } } }
Files.delete(bad); Files.delete(folder); }}Without cause: 10B: StorageException 10C: StorageException With cause: 10B: StorageException <- NoSuchFileException 10C: StorageException <- NumberFormatException
What this code does
- Class 10B fails because the file is missing; class 10C fails because a line holds
abinstead of a number. Without the cause, both errors are an identicalStorageException. - With
new StorageException(msg, e), thechainloop walksgetCause()and shows the real reason for each. Logs and stack traces get the same information throughCaused by:.
Without the cause, a missing file and a corrupt line produce the same "Could not load" message and nobody can tell them apart. With it, getCause() and the Caused by: section of the stack trace show the real problem: NoSuchFileException in one case, NumberFormatException in the other.
Order of execution
Follow the exception upward
Tap the steps in the order they happen when 10B.csv is missing.
e along, the most useful part of the error is gone.Not leaking file paths to the caller
The message of an IOException is often a full path, such as C:\Users\riya\AppData\fees\10B.csv. Shown to a user, it reveals the Windows user name and the folder layout, and it gives the user nothing they can act on.
Example 4 · The UI shows a safe message; the path stays in the cause
import java.io.IOException;import java.nio.file.Files;import java.nio.file.NoSuchFileException;import java.nio.file.Path;import java.util.List;
class StorageException extends RuntimeException { StorageException(String message, Throwable cause) { super(message, cause); }}
class MarksStorage { private final Path folder;
MarksStorage(Path folder) { this.folder = folder; }
List<String> load(String className) { try { return Files.readAllLines(folder.resolve(className + ".csv")); } catch (IOException e) { throw new StorageException("Could not load marks for class " + className, e); } }}
public class SafeMessageDemo { public static void main(String[] args) throws IOException { Path folder = Files.createTempDirectory("marks"); MarksStorage storage = new MarksStorage(folder);
try { storage.load("10B"); } catch (StorageException e) { Throwable cause = e.getCause(); boolean leaks = cause.getMessage().contains(folder.toString()); System.out.println("Raw IOException message contains the full folder path: " + leaks);
System.out.println("User sees: Sorry, marks for class 10B are not available right now.");
String fileName = cause instanceof NoSuchFileException nsf ? Path.of(nsf.getFile()).getFileName().toString() : "unknown"; System.out.println("Developer log: " + e.getMessage() + " (cause " + cause.getClass().getSimpleName() + ", file " + fileName + ")"); }
Files.delete(folder); }}Raw IOException message contains the full folder path: true User sees: Sorry, marks for class 10B are not available right now. Developer log: Could not load marks for class 10B (cause NoSuchFileException, file 10B.csv)
What this code does
- The message of a
NoSuchFileExceptionis the full path, which on a real machine includes the user's folder name. Printing it on screen would leak that detail and still not help the user. - The user gets a sentence about class 10B. The developer line keeps the technical facts: the app message, the cause type and the file name from
getFile(). The next lessons send such lines to a real log.
So the message that crosses into the UI uses a logical name ("marks for class 10B"), and the path stays inside the cause, where only logs and developers see it. The UI then turns the app exception into a friendly sentence. The next lesson covers what a good user message says.
Next step
Check your understanding
12 quick questions