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

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

    This is the function I use to modify the exception message in Python 2.7 and 3.x while preserving the original traceback. It requires six

    def reraise_modify(caught_exc, append_msg, prepend=False):
        """Append message to exception while preserving attributes.
    
        Preserves exception class, and exception traceback.
    
        Note:
            This function needs to be called inside an except because
            `sys.exc_info()` requires the exception context.
    
        Args:
            caught_exc(Exception): The caught exception object
            append_msg(str): The message to append to the caught exception
            prepend(bool): If True prepend the message to args instead of appending
    
        Returns:
            None
    
        Side Effects:
            Re-raises the exception with the preserved data / trace but
            modified message
        """
        ExceptClass = type(caught_exc)
        # Keep old traceback
        traceback = sys.exc_info()[2]
        if not caught_exc.args:
            # If no args, create our own tuple
            arg_list = [append_msg]
        else:
            # Take the last arg
            # If it is a string
            # append your message.
            # Otherwise append it to the
            # arg list(Not as pretty)
            arg_list = list(caught_exc.args[:-1])
            last_arg = caught_exc.args[-1]
            if isinstance(last_arg, str):
                if prepend:
                    arg_list.append(append_msg + last_arg)
                else:
                    arg_list.append(last_arg + append_msg)
            else:
                arg_list += [last_arg, append_msg]
        caught_exc.args = tuple(arg_list)
        six.reraise(ExceptClass,
                    caught_exc,
                    traceback)
    

提交回复
热议问题