Why did you choose to use the finally statement instead of the catch statement? (JAVA)

I'm new to Java and I'm still trying to understand the basics I've been learning exception handling in the form of try catch statements These are good, and I understand how and why I should use them What puzzles me is the try finally statement

More specifically, I don't understand why I can't just use catch statements to do the same thing What are the benefits of choosing to put some commands in a finally statement instead of the same statement in a catch statement? Won't these statements be executed in exactly the same way?

Sorry, if this is a stupid or naive question I just can't fully understand the benefits of using finally statements

Solution

Catch: when a problem occurs Finally: when / nothing went wrong Just as you want to close the database connection regardless of whether an exception is thrown or not, in this case, it will eventually be the best place to put the code In addition, if you have multiple catch blocks with redundant code, you can move the redundant part to the finally block

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>