python自定义异常捕获异常处理异常

2021-01-22 14:22:44 浏览数 (1)

参考链接: Python自定义异常

def set_inf(name,age):

    if not 0 < age < 120:

        raise ValueError('超出范围')

    else:

        print('%s is %s years old' % (name,age))

def set_inf2(name,age):

    assert 0 < age < 120,'超出范围'

    print('%s is %s years old' % (name,age))

if __name__ == '__main__':

    try:

      set_inf('bob',200)

    except ValueError as e:

        print('无效值:',e)

    set_inf2('bob',200)

0 人点赞