课时32 异常处理:你不可能总是对的

目录

 

一、什么是异常

二、异常的总结


一、什么是异常

程序出现逻辑错误或者用户输入不合法都会引起异常,但这些异常并不是致命的,不会导致程序崩溃死掉。可以利用Python提供的异常处理机制,在异常出现的时候及时捕获,并从内部消化掉。

看下面的这个例子,当用户输入一个不存在的文件名,那么程序就会报错:

file_name = input('请输入需要打开的文件名:')
f = open(file_name)
print('文件的内容是:')
for each_line in f:
    print(each_line)

抛出一个FileNotFoundError的异常

Traceback (most recent call last):
  File "C:/Users/ZPWX/AppData/Local/Programs/Python/Python37/源码/032/note1.py", line 2, in <module>
    f = open(file_name)
FileNotFoundError: [Errno 2] No such file or directory: 'test.txt'

二、异常的总结

  • AssertionError:断言语句(assert)失败

断言语句在关于分支和循环的章节里讲过。当assert这个关键字后边的条件为假的时候,程序将停止并抛出AssertionError异常。assert语句一般是在测试程序的时候用于在代码中置入检查点:

>>> my_list = ['我爱Pyhon']
>>> assert len(my_list) > 0
>>> my_list.pop ()
'我爱Pyhon'
>>> assert len(my_list) > 0
Traceback (most recent call last):
  File "<pyshell#4>", line 1, in <module>
    assert len(my_list) > 0
AssertionError
  • AttributeError:尝试访问未知的对象属性
>>> my_list.fishc
Traceback (most recent call last):
  File "<pyshell#6>", line 1, in <module>
    my_list.fishc
AttributeError: 'list' object has no attribute 'fishc'
  • IndexError:索引超出序列的范围
>>> my_list = [1,2,3]
>>> my_list[3]
Traceback (most recent call last):
  File "<pyshell#8>", line 1, in <module>
    my_list[3]
IndexError: list index out of range
>>> my_list[2]
3
  • KeyError:字典中查找一个不存在的关键字
>>> my_dict = {'one':1,'two':2,'three':3}
>>> my_dict['one']
1
>>> my_dict['four']
Traceback (most recent call last):
  File "<pyshell#13>", line 1, in <module>
    my_dict['four']
KeyError: 'four'

字典不支持索引,可以用get()方法来查找,当查找不存在的关键字,不会报错

  • NameError:尝试访问一个不存在的变量

当尝试访问一个不存在的变量时,Python会抛出此类异常

>>> fishc
Traceback (most recent call last):
  File "<pyshell#15>", line 1, in <module>
    fishc
NameError: name 'fishc' is not defined
  • OSError:操作系统产生的异常

OSError顾名思义就是操作系统产生的异常,像打开一个不存在的文件会引发FileNotFoundError,而这个FileNotFoundError就是OSError的子类。例子上面已经演示过,这里就不重复了。

  • SyntaxError:python语法错误

遇到此类错误是Python语法的错误,这是Python的代码并不能继续执行,应该先找到并改正错误:

>>> print 'i love python'
SyntaxError: Missing parentheses in call to 'print'. Did you mean print('i love python')?
  • TypeError:不同类型间的无效操作
>>> 1 + '1'
Traceback (most recent call last):
  File "<pyshell#20>", line 1, in <module>
    1 + '1'
TypeError: unsupported operand type(s) for +: 'int' and 'str'
  • ZeroDivisionError:除数为零
>>> 5 / 0
Traceback (most recent call last):
  File "<pyshell#19>", line 1, in <module>
    5 / 0
ZeroDivisionError: division by zero

Python标准异常总结点击这里

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值