zoukankan      html  css  js  c++  java
  • 10.异常

    常见异常:

    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('结束')
     
  • 相关阅读:
    js:鼠标事件
    js:argument
    js:|| 和 && 运算符 特殊用法
    css:选择器
    css:清除浮动 overflow
    jquery:after append appendTo三个函数的区别
    WIndow Document
    css:颜色名和十六进制数值
    安装centos出错
    Leetcode | Unique Paths I & II
  • 原文地址:https://www.cnblogs.com/fly-book/p/11738594.html
Copyright © 2011-2022 走看看