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

前端 未结 12 1119
情书的邮戳
情书的邮戳 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 10:02

    This only works with Python 3. You can modify the exception's original arguments and add your own arguments.

    An exception remembers the args it was created with. I presume this is so that you can modify the exception.

    In the function reraise we prepend the exception's original arguments with any new arguments that we want (like a message). Finally we re-raise the exception while preserving the trace-back history.

    def reraise(e, *args):
      '''re-raise an exception with extra arguments
      :param e: The exception to reraise
      :param args: Extra args to add to the exception
      '''
    
      # e.args is a tuple of arguments that the exception with instantiated with.
      #
      e.args = args + e.args
    
      # Recreate the expection and preserve the traceback info so thta we can see 
      # where this exception originated.
      #
      raise e.with_traceback(e.__traceback__)   
    
    
    def bad():
      raise ValueError('bad')
    
    def very():
      try:
        bad()
      except Exception as e:
        reraise(e, 'very')
    
    def very_very():
      try:
        very()
      except Exception as e:
        reraise(e, 'very')
    
    very_very()
    

    output

    Traceback (most recent call last):
      File "main.py", line 35, in 
        very_very()
      File "main.py", line 30, in very_very
        reraise(e, 'very')
      File "main.py", line 15, in reraise
        raise e.with_traceback(e.__traceback__)
      File "main.py", line 28, in very_very
        very()
      File "main.py", line 24, in very
        reraise(e, 'very')
      File "main.py", line 15, in reraise
        raise e.with_traceback(e.__traceback__)
      File "main.py", line 22, in very
        bad()
      File "main.py", line 18, in bad
        raise ValueError('bad')
    ValueError: ('very', 'very', 'bad')
    

提交回复
热议问题