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

前端 未结 12 1133
情书的邮戳
情书的邮戳 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条回答
  •  半阙折子戏
    2020-12-12 09:57

    Update: For Python 3, check Ben's answer


    To attach a message to the current exception and re-raise it: (the outer try/except is just to show the effect)

    For python 2.x where x>=6:

    try:
        try:
          raise ValueError  # something bad...
        except ValueError as err:
          err.message=err.message+" hello"
          raise              # re-raise current exception
    except ValueError as e:
        print(" got error of type "+ str(type(e))+" with message " +e.message)
    

    This will also do the right thing if err is derived from ValueError. For example UnicodeDecodeError.

    Note that you can add whatever you like to err. For example err.problematic_array=[1,2,3].


    Edit: @Ducan points in a comment the above does not work with python 3 since .message is not a member of ValueError. Instead you could use this (valid python 2.6 or later or 3.x):

    try:
        try:
          raise ValueError
        except ValueError as err:
           if not err.args: 
               err.args=('',)
           err.args = err.args + ("hello",)
           raise 
    except ValueError as e:
        print(" error was "+ str(type(e))+str(e.args))
    

    Edit2:

    Depending on what the purpose is, you can also opt for adding the extra information under your own variable name. For both python2 and python3:

    try:
        try:
          raise ValueError
        except ValueError as err:
           err.extra_info = "hello"
           raise 
    except ValueError as e:
        print(" error was "+ str(type(e))+str(e))
        if 'extra_info' in dir(e):
           print e.extra_info
    

提交回复
热议问题