pythonexceptionerror-handling

Is it right to raise an error in except block in python?


I often see code like this:

try:
    some_operation()
except Exception:
    logger.error("An error occurred while running the operation")
    raise Exception("A custom message")

Please ignore using the general Exception in this example, I know it's a bad practice. You can think of any other more specific subclasses of Exception.

I don't feel fine with code like this. What is the purpose of catching an exception if it's raised again, maybe with modified message? If a developer does it for logging or changing the class of the exception is it OK and good approach? I understand try...except blocks (in any language) to really handle exceptions. The example I showed is for me not good, but maybe it's a common practice in python world? Is it? Is there a more proper way for logging in such cases?


Solution

  • This general pattern is an accepted practice. It allows a more meaningful message to be written for the user of the code as well as logging a more meaningful message for the developer. From the docs:

    The most common pattern for handling Exception is to print or log the exception and then re-raise it (allowing a caller to handle the exception as well):

    import sys
    
    try:
        f = open('myfile.txt')
        s = f.readline()
        i = int(s.strip())
    except OSError as err:
        print("OS error:", err)
    except ValueError:
        print("Could not convert data to an integer.")
    except Exception as err:
        print(f"Unexpected {err=}, {type(err)=}")
        raise