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

前端 未结 12 1122
情书的邮戳
情书的邮戳 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:59

    It seems all the answers are adding info to e.args[0], thereby altering the existing error message. Is there a downside to extending the args tuple instead? I think the possible upside is, you can leave the original error message alone for cases where parsing that string is needed; and you could add multiple elements to the tuple if your custom error handling produced several messages or error codes, for cases where the traceback would be parsed programmatically (like via a system monitoring tool).

    ## Approach #1, if the exception may not be derived from Exception and well-behaved:
    
    def to_int(x):
        try:
            return int(x)
        except Exception as e:
            e.args = (e.args if e.args else tuple()) + ('Custom message',)
            raise
    
    >>> to_int('12')
    12
    
    >>> to_int('12 monkeys')
    Traceback (most recent call last):
      File "", line 1, in 
      File "", line 3, in to_int
    ValueError: ("invalid literal for int() with base 10: '12 monkeys'", 'Custom message')
    

    or

    ## Approach #2, if the exception is always derived from Exception and well-behaved:
    
    def to_int(x):
        try:
            return int(x)
        except Exception as e:
            e.args += ('Custom message',)
            raise
    
    >>> to_int('12')
    12
    
    >>> to_int('12 monkeys')
    Traceback (most recent call last):
      File "", line 1, in 
      File "", line 3, in to_int
    ValueError: ("invalid literal for int() with base 10: '12 monkeys'", 'Custom message')
    

    Can you see a downside to this approach?

提交回复
热议问题