What is the essence of the final solution try catch / except finally

For many years I used try-catch / except-finally variants in many languages, today someone asked me what was the point, and I could not answer.

Basically, why did you put the statement in the end instead of just putting it after the whole try-catch block? Or, in other words, there is a difference between the following blocks of code:

try{ //a} catch {//b} finally {//c} try{//a} catch{//b} //c 

EDIT:
PEOPLE, I know what he ultimately does, I have been using it for ages, but my question is in the above example, setting //c , in the end, seems redundant, doesn't it?

+43
exception-handling finally
Mar 13 '12 at 16:16
source share
3 answers

The purpose of the finally block is to ensure that the code runs in three circumstances that will not be very carefully processed using only catch blocks:

  • If the code in the try block exits via return
  • If the code in the catch block either jumps the caught exception, or - accidentally or intentionally - ends up throwing a new one.
  • If the code in the try block encounters an exception for which there is no catch.

You can copy the finally code before each return or throw and wrap catch blocks within their own try / catch to allow for the possibility of a random exception, but it is much easier to discard all of this and just use the finally block.

By the way, I would like language designers to include an exception argument for the finally block, to deal with the case when you need to clear after the exception, but still want it to leak the call (for example, you could build the code for the constructor in such a construction and Dispose object being built if the constructor was going to exit with an exception)

+61
Mar 13 '12 at 16:30
source share

Finally make sure your code is executed even if you get an exception.

The finally block is useful for clearing any resources allocated in the try block, as well as for running any code that should be executed, even if an exception exists.

http://msdn.microsoft.com/en-us/library/zwc8s4fz(v=vs.80).aspx

+1
Mar 13 2018-12-12T00:
source share

Finally, the block is executed even if an exception is thrown in the try block. Therefore, for example, if you opened a stream earlier, you may need to close this stream, otherwise an exception will be thrown. Finally, a block is useful for such a problem.

0
Mar 13 2018-12-12T00:
source share



All Articles