On 11/25/2015 01:59 AM, Martin Buchholz wrote:


On Tue, Nov 24, 2015 at 2:30 PM, Peter Levart <peter.lev...@gmail.com <mailto:peter.lev...@gmail.com>> wrote:


    What do you think of exception cloning?


Making copies of java objects has historically been troublesome (e.g. Cloneable). I have made clones of objects often in tests via deserialization + reserialization, but never in serious code. So I'm hesitant. We could try to make the serial clone + addSuppressed, and fall back to the original exception in case of failure. This might work well in practice. We might also discover lots of latent serialization bugs in exceptions. Has decades of RMI caught most of the problems with this approach? Can we have a serialization expert bless this?


I was only thinking of Cloneable. Serialization is troublesome. If Throwable was retrofitted to implement Cloneable and have the following new static method:

    /**
* {@link Object#clone() Clones} given {@code exception} and returns it's clone which * shares all state with original exception (shallow clone) except for the possible list of already * {@link #addSuppressed(Throwable) added} {@link #getSuppressed() suppressed} * exceptions. The suppressed exception instances are not cloned, just the * list containing them. Further {@link #addSuppressed(Throwable) additions}
     * to the suppressed exceptions of the returned clone instance
* don't affect the suppressed exceptions of original exception and vice versa.
     *
     * @param exception the exception to clone.
     * @param <T>       the type of exception
     * @return shallow clone of given exception with suppressed exception
     * list shallow-cloned
     * @since 1.9
     */
    @SuppressWarnings("unchecked")
    public static <T extends Throwable> T clone(T exception) {
        try {
            Throwable clone = (Throwable) exception.clone();
            if (clone.suppressedExceptions != null &&
                clone.suppressedExceptions != SUPPRESSED_SENTINEL) {
clone.suppressedExceptions = new ArrayList<>(clone.suppressedExceptions);
            }
            return (T) clone;
        } catch (CloneNotSupportedException e) {
            throw new InternalError(e);
        }
    }


...then would you prefer using it or would you nevertheless prefer swapping the roles of exceptions in whenComplete?

Regards, Peter

Reply via email to