I’m relatively new to Java and I’m still trying to understand the fundamentals. I have been learning about exception handling in the form of try-catch statements. These are fine and I understand how and why I should make use of them. The thing that has confused me is the try-finally statements.
To be more specific I don’t see why I can’t just use a catch statement to do the same thing. What is the benefit of choosing to put some commands in a finally statement as opposed to putting the same statements in the catch statement? Won’t the statements still be executed in exactly the same way?
Sorry if this is a silly or naive question. I just can’t quite work out the benefits of using the finally statement.
catch: When something goes wrong.finally: When something / nothing goes wrong.Like if you want to close database connection irrespective of whether an exception is thrown or not, In such case
finallywill be best place to put your code.Also if you have multiple catch blocks with some redundant code, you can move redundant part to
finallyblock.