JavaSa
JavaSa

Reputation: 6241

Raising exception from within except clause

I'm wondering if we can do something like the following:
We catch socket error and if the message is different than some value,
raise the exception forward to be caught on the next general except clause below?

try:
    some logic to connect to a server..   

except socket.error as se:
    if se.messsage != '123':
       raise Exception(se.message)
except exception as ex:
    log.error('write something')

Upvotes: 4

Views: 4484

Answers (2)

Swakeert Jain
Swakeert Jain

Reputation: 776

To do this, you need a set of try-catch blocks. Once, an exception has been caught, re-throwing the exception results in it being caught at the outer level. Try if else inside the blocks or simply nest try-except block in another one like this:

try:
    try:
        #...
    except:
        raise
except:
    pass

Upvotes: 2

Klaus D.
Klaus D.

Reputation: 14369

You can simply re-raise the exception with raise without arguments:

try:
    # some code
except:
    if condition:
        raise

Upvotes: 0

Related Questions