BanksySan
BanksySan

Reputation: 28510

What causes the recursive cause in an exception?

When looking at an exception in Java in a debugger you will often see that the cause is recursive to itself infinitely (I assume it's infinite).

e.g:

Exception1, 
  Caused by -> Exception2 
     Caused by -> Exception2
        Caused by -> Exception2 

Why is this?

NB: This is when looking at the code in a debugger, Eclipse in this case.

Upvotes: 11

Views: 3061

Answers (1)

ewan.chalmers
ewan.chalmers

Reputation: 16235

Looking at the source code of Throwable:

  187       /**
  188        * The throwable that caused this throwable to get thrown, or null if this
  189        * throwable was not caused by another throwable, or if the causative
  190        * throwable is unknown.  If this field is equal to this throwable itself,
  191        * it indicates that the cause of this throwable has not yet been
  192        * initialized.
  193        *
  194        * @serial
  195        * @since 1.4
  196        */
  197       private Throwable cause = this;

So I guess what you are seeing is an Exception which was created without using one of the constructors which takes a cause.

You will see this in a debugger, but getCause takes care of not returning the recursive reference:

  414       public synchronized Throwable getCause() {
  415           return (cause==this ? null : cause);
  416       }

Upvotes: 20

Related Questions