Exception Chaining in Java
Exception chaining preserves an original exception as the cause of a new one, rather than losing that original information when translating a low-level failure into a higher-level, more meaningful exception — throw new ServiceException("Failed to load user", originalException); wraps originalException as the new exception's cause, keeping its full stack trace and message intact and accessible. Without chaining, catching a low-level exception and throwing a different, more meaningful one in its place would silently discard exactly the detail that's most useful for genuinely diagnosing the root problem later.
getCause() retrieves that wrapped original exception from the new one, and a printed stack trace for a chained exception shows both exceptions together, clearly labeled, with the original cause's trace appearing right underneath the wrapping exception's own. No diagnostic detail from the original failure is actually lost, even though the code that catches it deals with the new, more meaningful exception type instead.
The problem chaining solves
Translating a low-level exception into a more meaningful one can lose the original failure's detail if that original isn't explicitly preserved.
Passing the original as a cause
Most exception constructors accept a Throwable as a second argument specifically for this purpose.
getCause()
Retrieves the originally wrapped exception from a chained one, when it's actually needed for diagnosis.
Stack traces show the full chain
Both the wrapping exception's own trace and the original cause's trace appear together, clearly connected.
When chaining matters most
Anywhere a lower-level technical exception, like from a database or file, gets translated into a higher-level, more meaningful one for callers.
public class ChainingDemo { static void loadConfig() throws Exception { try { throw new NumberFormatException("bad port value"); } catch (NumberFormatException e) { throw new Exception("Failed to load configuration", e); } } public static void main(String[] args) { try { loadConfig(); } catch (Exception e) { System.out.println("Caught: " + e.getMessage()); System.out.println("Caused by: " + e.getCause().getMessage()); } }}Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in Java yourself — building beats watching.