[Python] How do I raise the same Exception with a custom message in Python?

Discussão em 'Python' iniciado por Stack, Março 11, 2025.

  1. Stack

    Stack Membro Participativo

    I have this try block in my code:

    try:
    do_something_that_might_raise_an_exception()
    except ValueError as err:
    errmsg = 'My custom error message.'
    raise ValueError(errmsg)


    Strictly speaking, I am actually raising another ValueError, not the ValueError thrown by do_something...(), which is referred to as err in this case. How do I attach a custom message to err? I try the following code but fails due to err, a ValueError instance, not being callable:

    try:
    do_something_that_might_raise_an_exception()
    except ValueError as err:
    errmsg = 'My custom error message.'
    raise err(errmsg)

    Continue reading...

Compartilhe esta Página