Python: throw an exception through a Try / Except block with a few exceptions

Is there a way to throw an exception in a try / except block from one other than the next?

I want to catch a specific error, and then perform general error handling.

"raise" allows you to exclude "bubble up" for an external try / except, but not inside the try / except block that caused the error.

Ideally, there should be something like this:

import logging def getList(): try: newList = ["just", "some", "place", "holders"] # Maybe from something like: newList = untrustedGetList() # Faulty List now throws IndexError someitem = newList[100] return newList except IndexError: # For debugging purposes the content of newList should get logged. logging.error("IndexError occured with newList containing: \n%s", str(newList)) except: # General errors should be handled and include the IndexError as well! logging.error("A general error occured, substituting newList with backup") newList = ["We", "can", "work", "with", "this", "backup"] return newList 

The problem is that when an IndexError gets bound to the first, except mine, the general error handling in the second exclusive block is not applied.

The only workaround I have now is to include a common error handling code in the first block. Even if I pack it in my own function block, it still seems less elegant ...

+5
source share
1 answer

You have two options:

  • Do not catch IndexError with the selected except .. block. You can always manually check the type of exception in the general block by catching BaseException and assigning a name exception (here e ):

     try: # ... except BaseException as e: if isinstance(e, IndexError): logging.error("IndexError occured with newList containing: \n%s", str(newList)) logging.error("A general error occured, substituting newList with backup") newList = ["We", "can", "work", "with", "this", "backup"] return newList 
  • Use the nested try..except and re-raise:

     try: try: # ... except IndexError: logging.error("IndexError occured with newList containing: \n%s", str(newList)) raise except: logging.error("A general error occured, substituting newList with backup") newList = ["We", "can", "work", "with", "this", "backup"] return newList 
+3
source

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


All Articles