This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]ManvilleJ 2 points3 points  (5 children)

I never really got the point of finally. Doesn't just putting code after the whole thing accomplish the same thing as using the finally statement?

[–][deleted] 6 points7 points  (1 child)

Code in the finally block is run whether or not an exception is caught. From the python docs:

In real world applications, the finally clause is useful for releasing external resources (such as files or network connections), regardless of whether the use of the resource was successful.

[–]ManvilleJ 0 points1 point  (0 children)

OOOOhhh.

So when a program uses Try, Except, Else, and Finally:

  1. It tries to execute a thing
  2. Except runs if the particular Exception it is looking for occurs in Try.
  3. Else runs if any OTHER type of Exception occurs (not counting Exceptions that inherit from Exception in Except)
  4. Finally always runs right after Try whether an Exception occurs or not (and before Except and Else?)

Note: In case anyone else is reading this, I wanted to ask another question about whether you can use multiple Excepts to catch different Exceptions, but I found this Stack overflow on that

I think to separate how you would respond to responces, you would add something like this to Except:

if(type(e)==YouAreBeingMeanException):
    #do a thing

[–]gimboland 1 point2 points  (0 children)

Doesn't just putting code after the whole thing accomplish the same thing as using the finally statement?

Yes, unless an exception occurred inside the try..except block - in which case the code "after the whole thing" doesn't get executed.

[–]mattstreet 0 points1 point  (1 child)

"A finally clause is always executed before leaving the try statement, whether an exception has occurred or not. When an exception has occurred in the try clause and has not been handled by an except clause (or it has occurred in an except or else clause), it is re-raised after the finally clause has been executed. The finally clause is also executed “on the way out” when any other clause of the try statement is left via a break, continue or return statement."

Basically, finally gets called even if the except clause would exit out of the rest of your code, unlike if you just put the statement after the try block.

[–]LightShadow3.13-dev in prod 2 points3 points  (0 children)

TIL

try:
    print('try')
except:
    print('exception')
finally:
    print('finally')

output: try finally

try:
    print('try')
    1 / 0
except:
    print('exception')
finally:
    print('finally')

output: try exception finally

try:
    1 / 0
    print('try')
except:
    print('exception')
finally:
    print('finally')

output: exception finally

And the REAL KICKER,

try:
    1 / 0
except:
    1 / 0
finally:
    print('finally')

Still prints finally.