1

can somebody help me with the following piece of the code:

try:
    #do some things
    myClass.close()
except Exception, error:
    myClass.close()
    raise error

as You see I can't use here finally because in that case I will not know if an error actually occured, and I need to raise this error (raise error)

my question is how can I avoid using this two times myClass.close()? thanks in advance for any help

yeap
  • 307
  • 5
  • 12
  • 4
    Please **never** re-raise exception in this way. **Always** use a plain `raise` for this purpose. Otherwise you lose the original backtrace which is pretty annoying in most cases. – ThiefMaster Sep 11 '11 at 16:31

6 Answers6

2

You can use finally :)

This should do what you want:

try:
    #do some things
finally:
    myClass.close()
Wolph
  • 78,177
  • 11
  • 137
  • 148
2

This is equivalent to your code:

try:
    #do some things
finally:
    myClass.close()

First it calls myClass.close() and if there was a error it is raised again.

You can also have this to handle specific exceptions:

try:
    #do some things
except Exception, error:
    raise # re-raise the original exception
finally:
    myClass.close()
Jochen Ritzel
  • 104,512
  • 31
  • 200
  • 194
  • 1
    Use only `raise` to re-raise the exception instead of using `raise error` to keep the backtrace of the original exception. – ThiefMaster Sep 11 '11 at 16:32
  • What happens if the close itself raises an exception in the various cases (e.g. - an exception was already raised in the try block)? Can / should you wrap the close inside the finally block in another try block that swallows any / all exceptions the close raises? Will that preserve the previous exception raised in the original try block? – jschultz410 Nov 05 '19 at 22:11
1

You can chain try, except and finally since Python 2.5:

try:
    # Do some things...
    pass
except Exception, error:
    # Log the error...
    raise
finally:
    myClass.close()
Frédéric Hamidi
  • 258,201
  • 41
  • 486
  • 479
1

Next to a finally (that would work) you could also use a context manager that calls your myClass.close() method on exit.

0

Nest it.

try:
  try:
    ...
  except ...:
    raise error
finally:
  myClass.close()
Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
0

Regardless this will not work. If you already raised an exception/error the first time you invoked myClass.close(), calling it again will be of no help. The error handling keywords are for implementing fallbacks, reporting and routing of the error-flow.

See here for error handling: Can I get the exception from the finally block in python?

Community
  • 1
  • 1
Lorenz Lo Sauer
  • 23,698
  • 16
  • 85
  • 87