Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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')
like image 803
JavaSa Avatar asked Oct 24 '25 19:10

JavaSa


1 Answers

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
like image 167
Swakeert Jain Avatar answered Oct 26 '25 08:10

Swakeert Jain



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!