is it good practice to call a method from Exception block in java?

This is bad practice for two reasons:

  1. Normally, cleanup kind of actions … should also be executed when your code doesn’t fail; right? But if you only put it into the catch … cleanup isn’t called when no exception is thrown!
  2. Beyond that: the above will not call cleanup() for subclasses of Throwable that are not Exceptions.

So, the one and only way to do such things is to use the finally block in order to call methods … that should always be called. Or, depending on the actual problem at hand, you might want to look into using try-with-resources and the AutoCloseable interface.

Leave a Comment