常见异常:

try...except...finally:

try:
    i = int(input('count:'))
    i = i / 0
except ZeroDivisionError:
    print('除0了')
except ValueError as e:
    print('输入错误:', e)
finally: # 无论有没有异常都执行
    print('结束')

try...except...else:

try:
    i = int(input('count:'))
    # i = i / 0
except ZeroDivisionError:
    print('除0了')
except ValueError as e:
    print('输入错误:', e)
else: # 没有异常时执行
    print('没错误')
finally: # 无论有没有异常都执行
    print('结束')

同时处理多个异常:

try:
    i = int(input('count:'))
    # i = i / 0
except (ZeroDivisionError, ValueError) as e:
    print('错误:', e)
else:  # 没有异常时执行
    print('没错误')
finally:  # 无论有没有异常都执行
    print('结束')

raise:

try:
    i = int(input('count:'))
    i2 = int(input('count2:'))
    if i2 > i:
        raise ValueError('i2>i错误')  # 抛出异常
    i = i / i2
    # i = i / 0

except (ZeroDivisionError, ValueError) as e:
    print('错误:', e)
else:  # 没有异常时执行
    print('没错误')
finally:  # 无论有没有异常都执行
    print('结束')

assert:

try:
    i = int(input('count:'))
    i2 = int(input('count2:'))
    assert i2 > i  # 断言 # 不对会报AssertionError
    i = i / i2
    # i = i / 0

except (ZeroDivisionError, ValueError) as e:
    print('错误:', e)
else:  # 没有异常时执行
    print('没错误')
finally:  # 无论有没有异常都执行
    print('结束')
 
01-10 13:11