python自定义assert抛出的异常

方法一

常用于assert失败后的提示用语

assert 1 > 4, 'what?!'

异常为:

AssertionError: what?!

方法二

常用于assert失败后推断导致的报错

try:
    assert 1 > 4
except Exception as e:
    raise IOError

或是自定义一个报错:

class MyExcept(Exception):
    def __init__(self, message):
        Exception.__init__(self)
        self.message = message

    def __str__(self):
        return "自定义报错:%s" % self.message


if __name__ == '__main__':
    try:
        assert 1 > 4
    except Exception as e:
        raise MyExcept('something error')

你可能感兴趣的:(python,python)