JDK-8073382 : use lambdas to provide APIs that do automatic exception chaining, suppression, or wrapping
  • Type: Enhancement
  • Component: core-libs
  • Sub-Component: java.util
  • Priority: P5
  • Status: Open
  • Resolution: Unresolved
  • Submitted: 2015-02-18
  • Updated: 2015-08-14
Related Reports
Relates :  
Description
Investigate the addition of APIs that provide some lambda-based "syntactic sugar" to ease the chaining of exceptions. This might apply to the exception's cause-chain or the suppressed-exception list.

For example, consider this code:

    try {
        foo();
    } catch (Exception ex) {
        bar();
    }

If bar() were to throw an exception, the exception 'ex' originally thrown by foo() would be lost. The proper way to do this is to add any exceptions thrown by bar() to ex's suppressed exception list:

    try {
        foo();
    } catch (Exception ex) {
        try {
            bar();
        } catch (Exception ex2) {
            ex.addSuppressed(ex2);
        }
    }

It would be nicer if there were any API that would enable the following:

    try {
        foo();
    } catch (Exception ex) {
        ex.suppress(() -> bar());
    }

Or even

    Exception.suppress(() -> foo(), () -> bar());

Something similar could be worked up to chain exceptions to a new thrown exception's cause list.

Another possibility (perhaps warranting a separate bug report) is to provide a higher-order function that wraps any checked exceptions that a function might throw inside a RuntimeException.