Pregunta

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?

¿Fue útil?

Solución

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.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top