Calling methods that do not throw an exception in the "try" block

I have read some Java exceptions that handle best practices, but there is one point that is not covered in any literature I have seen. I have several methods to call only if the entire "try" block was successfully executed. Is it correct to call methods that do not throw any exceptions in the "try" block just because they only need to be called if the entire block has been successfully executed? Or is it better to make the success flag set to false in any catch block and call additional methods after the statement only if the flag is not false? Are there any style guides?

+3


source to share


3 answers


Can you do it. If you have something that needs to be done only if the try block succeeds, place it at the end of the try block. The Boolean flag is not needed.



If you need to run your code regardless of whether the try block succeeds, place it in a finally block.

+4


source


If you need this method, use a finally block anyway. Also you can use any method with any exception anywhere, including the catch block. Just handle these exceptions in this catch block. What it is is to provide another try / catch inside your catch block and do it as deeply as necessary.



+3


source


The only thing that matters is readability.

If you want to explicitly indicate that some methods need to be called only when the code is successfully executed in try

, then:

  • you can use some additional logic to express explicitly,
  • or you can use comments to make it clear.

In both cases, it should be obvious from the code.

+1


source







All Articles