What is the point of the finally block?

后端 未结 16 1110
长情又很酷
长情又很酷 2020-12-30 20:19

Syntax aside, what is the difference between

try {
}
catch() {
}
finally {
    x = 3;
}

and

try {
}
catch() {
}

x = 3;


        
相关标签:
16条回答
  • 2020-12-30 21:15

    Any code in the finally is ran in the even in the event of an unhandled exception. Typically the finally code is used to clean up local declarations of unmanaged code using .dispose().

    0 讨论(0)
  • 2020-12-30 21:16

    In Java:

    Finally always gets called, regardless of if the exception was correctly caught in catch(), or in fact if you have a catch at all.

    0 讨论(0)
  • 2020-12-30 21:17

    There are several things that make a finally block useful:

    1. If you return from the try or catch blocks, the finally block is still executed, right before control is given back to the calling function
    2. If an exception occurs within the catch block, or an uncaught type of exception occurs in the try block, the code in the finally block is still executed.

    These make finally blocks excellent for closing file handles or sockets.

    0 讨论(0)
  • 2020-12-30 21:17

    In Java, you use it for anything that you want to execute regardless of whether you used a "return", just ran through the try block, or had an exception caught.

    For example, closing a database session or a JMS connection, or deallocating some OS resource.

    I am guessing it is similar in .NET?

    0 讨论(0)
提交回复
热议问题