capypad
0 Tage Serie
java / intermediate
Snippet

Exception-Chaining für besseres Debugging

Exception-Chaining ermöglicht es, eine Low-Level-Exception (wie IOException) in eine Business-Exception auf höherer Ebene zu verpacken, während die ursprüngliche Ursache erhalten bleibt. Dies bewahrt den Stacktrace für das Debugging.

snippet.java
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);
}
}
Erklärung
1
catch (IOException e)
Fängt den spezifischen technischen Fehler ab, der aufgetreten ist.
2
throw new DataException(..., e);
Wirft eine neue Exception und übergibt 'e' als Ursache, damit der ursprüngliche Fehler nicht verloren geht.