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

Discussão em 'Python' iniciado por Stack, Julho 15, 2025.

  1. Stack

    Stack Membro Participativo

    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?

    Continue reading...

Compartilhe esta Página