2

I have read a lot of sources about debugging try,exception,finally . I do understand when we try some codes there are might be some exception. But I dont understand why sometimes we use finally when we already have exception?

1
  • 2
    finally is always executed. Sometimes code after exception may not get executed.. (Think about a situation that an exception is thrown within the exception block) Commented Jun 23, 2013 at 17:11

1 Answer 1

2

As it is indicated in the documentation, the finally clause is useful for releasing external resources, regardless of whether the use was successful. These external resources can be files or network connections, which require to be cleaned-up under all circumstances.

For instance:

try: f = open("testfile", "w") try: f.write("This may not work!") finally: f.close() except IOError: print("Error! Can't find file") 

The statement f.close() will always be executed, so even if the write operation raises an exception, the file will always be closed at the end.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.