java / intermediate
Snippet
Exception Chaining for Better Debugging
Exception chaining allows you to wrap a low-level exception (like IOException) into a higher-level business exception while preserving the original cause. This keeps the stack trace intact for debugging.
snippet.java
1
2
3
4
5
6
7
public void loadConfig() throws DataException {try {Files.readAllLines(Paths.get("config.txt"));} catch (IOException e) {throw new DataException("Configuration file missing", e);}}
Breakdown
1
catch (IOException e)
Catches the specific technical error that occurred.
2
throw new DataException(..., e);
Throws a new exception, passing 'e' as the cause so the root error is not lost.