20

I've come across some places in java libraries that I'm building against where the cause of an exception is set to the exception itself.

Is there any reason for the exception to reference itself as its cause?

EDIT

As requested, here is a concrete example:

enter image description here

4
  • 2
    Bad coding practice, if the exception is the cause already, it doesn't have to define a parent cause. Feb 10, 2012 at 19:30
  • 3
    Sure ... if you want to create a circular dependency from which there is no escape. I'm somehow thinking the code isn't doing what you think it's doing. Feb 10, 2012 at 19:32
  • Also bad practice, but it may happen that a code catches Exception X, and throws a new Exception X, with the old one as the cause. So they may look similar, but actually different exceptions.
    – Luciano
    Feb 10, 2012 at 20:00
  • When I've seen this, Eclipse shows the same object reference for both ex and ex.getCause().
    – Matt Mills
    Feb 11, 2012 at 5:56

4 Answers 4

24

I have frequently seen exceptions thrown by frameworks or libraries such as Hibernate or Spring reference themselves as the cause (confusing the debugger GUI in the process).

I always wondered why they did this since it seems like such a bad idea. And today it actually caused a problem when I was trying to serialize one to JSON : bam, enless cycle.

So I investigated it a bit further :

In the source code of Throwable (all source code listed here is from JDK 1.7) we have this :

 /**
     * The throwable that caused this throwable to get thrown, or null if this
     * throwable was not caused by another throwable, or if the causative
     * throwable is unknown.  If this field is equal to this throwable itself,
     * it indicates that the cause of this throwable has not yet been
     * initialized.
     *
     * @serial
     * @since 1.4
     */
    private Throwable cause = this;

Now I specifically met the problem with an exception class that extended RuntimeException, so I went from there. One of the constructors of RuntimeException :

/** Constructs a new runtime exception with the specified detail message.
     * The cause is not initialized, and may subsequently be initialized by a
     * call to {@link #initCause}.
     *
     * @param   message   the detail message. The detail message is saved for
     *          later retrieval by the {@link #getMessage()} method.
     */
    public RuntimeException(String message) {
        super(message);
    }

Constructor of Exception called by the above:

 /**
     * Constructs a new exception with the specified detail message.  The
     * cause is not initialized, and may subsequently be initialized by
     * a call to {@link #initCause}.
     *
     * @param   message   the detail message. The detail message is saved for
     *          later retrieval by the {@link #getMessage()} method.
     */
    public Exception(String message) {
        super(message);
    }

Constructor of Throwable called by the above :

/**
     * Constructs a new throwable with the specified detail message.  The
     * cause is not initialized, and may subsequently be initialized by
     * a call to {@link #initCause}.
     *
     * <p>The {@link #fillInStackTrace()} method is called to initialize
     * the stack trace data in the newly created throwable.
     *
     * @param   message   the detail message. The detail message is saved for
     *          later retrieval by the {@link #getMessage()} method.
     */
public Throwable(String message) {
    fillInStackTrace();
    detailMessage = message;
}

fillInStackTrace is a native method and desn't seem to modify the cause field.

So as you can see, unless the initCause method is called subsequently, the cause field is never changed from the original value of this.

Conclusion : if you create a new Exception (or one of the many many subclasses that exist in the wild and don't override this behaviour) using a constructor that doesn't take a cause argument, and you don't call the initCause method, the cause of the exception will be itself !

So I guess that should make it a very common occurrence.

2
  • 7
    You can indeed create an self-causing exception just doing Exception ex = new RuntimeException("ex"); But the ex.equals(ex.getCause()) will still return false because of the Throwable implementation: return this.cause == this?null:this.cause;
    – Vladimir
    Apr 12, 2017 at 20:29
  • 1
    true, but also look at Throwable.getCause() {return this.cause == this ? null : this.cause;}, and since cause is private it shouldn't bother you, the only value you'll see is what you get with getCause() and it's going to be null. If you look at exceptions in an IDE, that's another issue, but there it shouldn't be a problem either
    – Gavriel
    Jan 13, 2022 at 15:56
19

The accepted answer is misleading, and the other answers are incomplete. So...

While it would be bad design to pass in an exception as its own cause, it's not possible in the Throwable implementation for exactly that reason. The cause is either passed in during construction, or else to the initCause() method, and as pointed out in the second answer, the latter would lead to an IllegalArgumentException.

As the third answer points out, if you don't provide a cause, the cause will be this as per the Throwable implementation.

What's maybe missing (given the original question) is that the getCause() method of Throwable doesn't ever return this, it returns null if cause == this. So although your debugger is showing the this reference as the cause because it is using reflection, when using the public interface of Throwable you won't see it and so it won't be a problem.

1
  • 1
    Maybe you should re-edit your answer, because I have no idea which one is "accepted" answer, which one is "second", "third" now.
    – Chandler
    Apr 13, 2021 at 21:11
4

From the sources of Throwable I have here:

public synchronized Throwable initCause(Throwable cause) {
    ...
    if (cause == this)
        throw new IllegalArgumentException("Self-causation not permitted");
    ...
}

I don't see how setting cause to itself is possible at all.

2
  • IIRC, when I've seen this it has been in specific exceptions from the ORM layer. There's no reason to believe that because Throwable disallows it in the initCause method the exceptions I've seen behave the same way.
    – Matt Mills
    Feb 11, 2012 at 3:55
  • See Pierre Henry's answer to see how it's possible.
    – ctomek
    Oct 14, 2016 at 10:34
1

No, that's just bad design. If the exception is the root cause, it doesn't need to define a cause.

An exception that has a cause is a legit case for different exception wrappings. For example, if creating a persistence store, you might want to throw a PersistenceExcpetion. So then if it's a file store, you can have the cause be an IOException. If it's a database, maybe the cause is a SqlException. Etc

1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.