4
Reply

Why we need Finally key while we have catch?

Dharmendra Singh

Dharmendra Singh

11y
1.2k
0
Reply

    Aman Jain this is not good explanation, because if you are using catch the exception already handled and want to close connection here. so why you using finally.

    We use the finally block when we have something that has to be executed anyhow, whether the code in try works fine or gives exceptions and goes to catch. Take an example when you have a Sql query and you are doing some sql operation in try code, you will obviously need to close that connection after the work is completed. And suppose you got an exception somewhere and it goes in catch block, then also the connection needs to be closed. So, in such cases where we have to do something irrespective of which block is executed, (like closing the connection at the end), we use finally block and close the connection in this. Whether the execution is of TRY or CATCH, FINALLY will be executed after them.Hope you understood. :)

    This not good answer. Priti

    If you want to some operation after the successfully code execution of Try block.write code in finally block. like close connection etc.