0

I want to write a code like this:

try {
    try {
        someStuffThatCausesBusinessExceptions();
    } finally {
        try {
            cleanUp();
        } catch (Exception e) {
            // I don't really care
        }
    }
} catch (BusinessLogicException e) {
    // work with exception
    // cleaning up must be done by that point (or at least tried to)
}

Will exceptions from business logic survive the possible hiatus during cleanUp? Is there a better way to ignore all the possible exceptions from cleanUp?

Morse
  • 1,330
  • 2
  • 17
  • 27

3 Answers3

0

A catch block will only catch Throwables that were thrown in its corresponding try block. Thus, your exceptions thrown in the surrounding try block will be preserved and caught in the outer catch block.

O.O.Balance
  • 2,930
  • 5
  • 23
  • 35
0

Yes. Your exception will reach the last catch. However, this structure seems weird an non-idiomatic to me, i guess i would even prefer having cleanUp() more than once in that code over having 3 tries.

ZPiDER
  • 4,264
  • 1
  • 17
  • 17
0
There are two cases-:

1. if excetpion occurs from  mehtod someStuffThatCausesBusinessExceptions only then it will be caught in your outer catch block.

2. if the methods someStuffThatCausesBusinessExceptions and cleanUp both throw exceptions then the exception thrown from try block is suppressed.

Yes!! there is better way.You can use try-with-resources statement.

Please refere to this link.
https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html