Is it possible for the act of throwing an exception to throw a different exception instead?
In order to throw an exception one must (optionally) allocate the new object, and call its constructor (which implicitly calls fillinstacktrace). In some cases, it sounds like addSupressed is also called. So what happens if there isn’t enough memory? Is the JVM garuenteed to preallocate builtin exceptions? For instance, will (1/0) ever throw an OutOfMemoryError instead of an ArithmeticException?
Also, the constructor is a method call and hence can freely throw other exceptions. What happens in this case? Do builtin exceptions ever throw? Even if you don’t explicitly throw, it seems possible to get a StackOverflowError.
prints:
So, yes 🙂
In the case of built in exceptions, there’s a multitude of things that can go wrong. I do not believe that the spec requires the JVM to guarantee exception allocation succeeds, so an
OutOfMemoryErrorsounds like a distinct possibility. There’s also more obscure problems, such as class loading failures, that could happen. We can also get into the downright esoteric, where someone has modifiedjava.lang.Exceptionto cause an exception or error to throw.So, my opinion would be that you should expect / plan for that it is possible for exception handling to itself cause exceptions in extremely rare cases.