Python学习--Task08:异常处理

Python标准异常总结:

异常描述
AssertionError断言语句(assert)失败
AttributeError尝试访问未知的对象属性
EOFErrorinput()读取到EOF却没有接收到任何数据
FloatingPointError浮点计算错误
GeneratorExitgenerator.close()方法被调用的时候
ImportError导入模块失败的时候
IndexError索引超出序列的范围
KeyError字典中查找一个不存在的关键字
KeyboardInterrupt用户输入中断键(ctrl+c)
MemoryError内存溢出(可通删除对象释放内存)
NameError尝试访问一个不存在的变量
NotImplementedError尚未实现的方法
OSError操作系统产生的异常
OverflowError数值运算超出最大限制
ReferenceError弱引用试图访问一个已经被垃圾回收机制回收了的对象
RuntimeError一般运行时错误
StopIteration迭代器没有更多的值
SyntaxErrorPython的语法错误
IndentationError缩进错误
TabErrorTab和空格混合使用
SystemErrorPython编译器系统错误
SystemExitPython编译器进程被关闭
TypeError不同类型间的无效操作
UnboundLocalError访问一个未初始化的本地变量(NameError的子类)
UnicodeErrorUnicode相关的错误(ValueError的子类)
UnicodeEncodeErrorUnicode编码时的错误(UnicodeError的子类)
UnicodeDecodeErrorUnicode解码时的错误(UnicodeError的子类)
UnicodeTranslateErrorUnicode转换时的错误(UnicodeError的子类)
ValueError传入无效的参数
ZeroDivisionError除数为零

实例

  1. AssertionError
>>> my_list = ["NCEPU"]
>>> assert len(my_list) > 0
>>> my_list.pop()#去掉一个元素
'NCEPU'
>>> assert len(my_list) > 0
Traceback (most recent call last):
  File "<pyshell#3>", line 1, in <module>
    assert len(my_list) > 0
AssertionError
>>> 
  1. AttributeError
>>> my_list.fishc
Traceback (most recent call last):
  File "<pyshell#4>", line 1, in <module>
    my_list.fishc
AttributeError: 'list' object has no attribute 'fishc'
>>> 
  1. IndexError
>>> my_list2=[1,2,3]
>>> my_list2[3]
Traceback (most recent call last):
  File "<pyshell#11>", line 1, in <module>
    my_list2[3]
IndexError: list index out of range

检测异常

1. try-except语句

1)一般形式

try:
	检测范围
except Exception[as reason]:
	出现异常(Exception)后的处理代码

2) 实例

try:
    f=open("Python.txt")
    print(f.read())
    f.close()
except OSError as reason:
    print("文件出错\n错误的原因是:"+str(reason))

结果为:

文件出错
错误的原因是:[Errno 2] No such file or directory: 'Python.txt'

try后跟多个except语句:

try:
    sum=1+"1"
    f=open("Python100.txt")
    print(f.read())
    f.close()
except OSError as reason:
    print("文件出错\n错误的原因是:"+str(reason))
except TypeError as reason:
    print("类型出错\n错误的原因是:"+str(reason))

注:

  • try语句检测到异常就不会再执行下面语句,所以上程序只输出类型出错。
  • 也可以except (OSError,TypeError):

2. try-finally语句

1)一般形式

try:
 检测范围
except Exception[as reason]:
 出现异常(Exception)后的处理代码
finally:
	无论如何都会被执行的代码 

2)实例

try:
    f=open("Python1.txt","w")
    print(f.write("存在了"))
    sum=1+"1"
except (OSError,TypeError):
    print("出错了")
finally
    f.close()

3. raise语句

>>>raise NameError('HiThere')
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
NameError: HiThere
>>>try:
        raise NameError('HiThere')
    except NameError:
        print('An exception flew by!')
        raise
   
An exception flew by!
Traceback (most recent call last):
  File "<stdin>", line 2, in ?
NameError: HiThere

参考文献

https://www.bilibili.com/video/av4050443/?p=34
https://www.runoob.com/python3/python3-errors-execptions.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值