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

前端 未结 12 1111
情书的邮戳
情书的邮戳 2020-12-12 09:45

I have this try block in my code:

try:
    do_something_that_might_raise_an_exception()
except ValueError as err:
    errmsg = \'My custom error         


        
12条回答
  •  -上瘾入骨i
    2020-12-12 10:01

    Either raise the new exception with your error message using

    raise Exception('your error message')
    

    or

    raise ValueError('your error message')
    

    within the place where you want to raise it OR attach (replace) error message into current exception using 'from' (Python 3.x supported only):

    except ValueError as e:
      raise ValueError('your message') from e
    

提交回复
热议问题