Python 异常

异常语法

try:
    # 如果捕获到异常,后面的代码就不执行了
    # 不要把大片代码放在一个try里,然后使用pass忽略掉所有错误
    pass
except Exception as e:
    # except 必须有一个
    pass
except (Exception1, Exception2) as e:
    # 一次处理多个异常,放在元组里
    pass
except Exception as e:
    # all other exception
    pass
else:
    # 未捕获异常时执行 -- 可选
    pass
finally:
    # 无论异常是否发生,总会执行 -- 可选
    pass

异常分类

BaseException
    KyeboardInterrupt  用户按下ctrl+C
    SystemExit 应用程序退出
    Exception
        IOError  操作系统输入/输出错误(场景:尝试打开一个不存在的磁盘文件,或是 已经打开的文件)
        ZeroDivisionError  除数为0错误(场景:分母为0)
        IndexError  数组越界错误(场景:使用一个超出范围的之索引序列)
        keyError    字典key不存在(场景:使用错误的或是不存在的key)
        AttributeError  访问未知的对象属性(场景:对象属性没定义,如:A.cc)

        NameError   变量未定义(场景:访问一个没有初始化的变量,访问变量需要由解释器进行搜索)
            >>> a = []
            >>> del a   # 删除一个数值对象的引用
            >>> a
            Traceback (most recent call last):
              File "<stdin>", line 1, in <module>
            NameError: name 'a' is not defined

        TypeError   对象类型错误。函数或方法接受了不适当的【类型】的参数
            >>> float([])
            Traceback (most recent call last):
              File "<stdin>", line 1, in <module>
            TypeError: float() argument must be a string or a number, not 'list'

        ValueError  函数或方法虽然接受了正确的【类型】的参数,但是该参数的【值】不适当
            >>> float("adf")
            Traceback (most recent call last):
              File "<stdin>", line 1, in <module>
            ValueError: could not convert string to float: 'adf'

        AssertionError  断言异常
        assert 1==1
def open_file():
    try:
        f = open("sdf", "r")
    except Exception as e:
        print("couldn't open file: %s" % e)
        print(str(e))  # [Errno 2] No such file or directory: 'sdf'


# eg
def divide():
    try:
        num = int(input("input a number: "))
        res = 2/num
        print(res)
    except ZeroDivisionError as e:
        print("Denominator cannot be zero")
        print(str(e))  # division by zero  (input: 0)
    except ValueError as e:
        print("Please input correct number")
        print(str(e))  # invalid literal for int() with base 10: '3.3'  (# input: 3.3)


def safe_float(obj):
    try:
        # 设置局部变量,获取返回值
        retval = float(obj)
    except (ValueError, TypeError) as e:
        # 一次处理多个异常,将多个异常放到元组里
        retval = str(e)  # !!!
    return retval


if __name__ == '__main__':
    open_file()
    print()
    divide()  # input: 0
    divide()  # input: 3.3
    print()
    print(safe_float("sdf")) 
    print(safe_float([])) 
    print(safe_float(33.22))
card_data_file = "card_data.txt"
card_log_file = "card_log.txt"


def safe_float(obj):
    try:
        # 设置局部变量,获取返回值
        retval = float(obj)
    except (ValueError, TypeError) as e:
        # 一次处理多个异常,将多个异常放到元组里
        retval = str(e)  # !!!
    return retval


def main():
    "handle all the data processing"
    log = open(card_log_file, "w")
    try:
        ccfile = open(card_data_file, "r")
    except IOError as e:
        log.write("no txns this month\n")
        log.close()
        return

    # 读取文件内容
    txns = ccfile.readlines()
    ccfile.close()
    # 初始化total
    total = 0.00
    log.write("account log:\n")

    for each_txn in txns:
        # 有回车、空格,需要先处理一下!!!调用safe_float处理
        res = safe_float(each_txn.strip())
        if isinstance(res, float):
            # 判断res类型:如果是float类型,做加法
            total += res
            log.write("data: %s processed\n" % res)
        else:
            # 否则不做加法
            log.write("ignored: %s\n" % res)

    log.write("%s (new balance)" % total)
    log.close()
    return "%s (new balance)" % total  # 不用加括号


if __name__ == '__main__':
    print(main())
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值