1

Why is the stack trace Exception in thread "main" java.lang.ArithmeticException: 3 and not Exception in thread "main" java.lang.ArithmeticException: 1? Isn't ArithmeticException("1") thrown first?

 try{
        try{
            throw new ArithmeticException("1");
        }finally{
            throw new ArithmeticException("2");
        }
    }finally{
        throw new ArithmeticException("3");
    }
alwayscurious
  • 1,155
  • 1
  • 8
  • 18

1 Answers1

4

Yes, the "1" exception is thrown first. However:

Your finallys overwrite the exceptions thrown in the try blocks, so the finally exceptions are the only ones seen by the exception handling code.

Don't throw or return in a finally block, for precisely this reason.

See the description of this problem in Google's Error Prone documentation for a lot more detail.

Andy Turner
  • 137,514
  • 11
  • 162
  • 243
  • Nice and precise ... off-topic request: I put up this [question](https://stackoverflow.com/questions/47729575/is-there-a-way-of-gson-to-be-not-lenient-at-all) lately, and didn't see any feedback. I consider putting up a bounty - but before doing so: do you think the question is reasonable, or is there something I could improve? – GhostCat Dec 11 '17 at 07:32