Python 'except' pass-through

I was wondering if you can re-raise the (specific) caught exception and catch it later (in general), except for the same try-except. As an example, I want to do something with a specific IOError, but if its not an expected IOError, then the exception should be handled like any other error. I originally tried:

try: raise IOError() except IOError as ioerr: if ioerr.errno == errno.ENOENT: # do something with the expected err else: # continue with the try-except - should be handled like any other error raise except Exception as ex: # general error handling code 

However, this does not work: a raise repeatedly raises an exception outside the context of try-except. What would be the pythonic way of writing this in order to get the desired โ€œfailureโ€ exception?

(I know that a "conditional exception" was proposed that was not implemented, which could solve this)

+5
source share
2 answers

I am not an expert in pythonic writing, but I think that one obvious approach (if you know that you are expecting a specific exception) would be to use nested exception handling:

 try: try: raise IOError() except IOError as ioerr: if ioerr.errno == errno.ENOENT: # do something with the expected err else: # pass this on to higher up exception handling raise except Exception as ex: # general error handling code 

I know in my comment that you donโ€™t want the other nested - I donโ€™t know how the nested exception handling in your book is just as bad, but at least you can avoid code duplication.

+1
source

So, I'm working on it now, and after considering the available solutions, I'm going to go catch the parent exception and then check it for specifics. In my case, I am working with the dns module.

 try: answer = self._resolver.query(name, 'NS') except dns.exception.DNSException, e: #Superclass of exceptions tested for if isinstance(e, dns.resolver.NXDOMAIN): #Do Stuff elif isinstance(e, dns.resolver.NoAnswer): # Do other stuff else: # Do default stuff 
+1
source

Source: https://habr.com/ru/post/1234031/


All Articles