Can I create a Exception like
A a = new A (new B ( new A ) );
where A and B are two different type of Exception.
I know Java can do it but is it right to do that ?
Edit : I am writing an retry on type of Exception so I am checking the getCause of the Exception. I am breaking when getCause is null or getCause equal itself , Should I also break when getCause equals any Exception seen so far
This is legal.
You can also initialize the cause directly using the
initCause(Throwable)method.If you try to make exception its own cause; e.g.
you will get an
IllegalArgumentException("Self-causation not permitted"). (Thanks to Joachim Sauer for pointing that out.)While, the JVM will not stop you creating an indirect cycle, it is a really bad idea nonetheless.
It is an abuse of the
ThrowableAPI. It makes no logical sense for an exceptional event to have caused itself, directly or indirectly.There is likely be code out there that assumes that the “cause” chain of an exception doesn’t have any cycles. Such code is likely to fail in a nasty way if it ever encounters a pathological exception with a cause cycle.
Note that current generation (Java 7)
printStackTrace()detects and deals with a “cause” cycles, but earlier generations did not: