博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Python----面向对象---异常处理
阅读量:4338 次
发布时间:2019-06-07

本文共 4436 字,大约阅读时间需要 14 分钟。

一、什么是异常

异常是错误发生的信号,一旦程序出错,并且程序没有处理这个错误,那么就会抛出异常,并且程序的运行随之终止

例如:

1 print('1') 2 print('2') 3 print('3') 4 int('aaaa') 5 print('4') 6 print('5') 7 print('6') 8  9 结果为:10 11 Traceback (most recent call last):12 113 214   File "C:/Users/xu516/PycharmProjects/Python全栈开发/第三模块/面向对象编程/32 异常处理.py", line 6, in 
15 316 int('aaaa')17 ValueError: invalid literal for int() with base 10: 'aaaa'

报错后后面的代码没有被执行

二、错误分为两种

1、语法错误

例如:

1 print(xxx 2  3 if 1 > 3 4  5 结果为: 6  7   File "C:/Users/xu516/PycharmProjects/Python全栈开发/第三模块/面向对象编程/32 异常处理.py", line 15 8      9     ^10 SyntaxError: unexpected EOF while parsing

2、逻辑错误

 a、ValueError

1 int('aaa')2 3 结果为:4 5 Traceback (most recent call last):6   File "C:/Users/xu516/PycharmProjects/Python全栈开发/第三模块/面向对象编程/32 异常处理.py", line 15, in 
7 int('aaa')8 ValueError: invalid literal for int() with base 10: 'aaa'

b、NameError

1 name2 3 结果为:4 5 Traceback (most recent call last):6   File "C:/Users/xu516/PycharmProjects/Python全栈开发/第三模块/面向对象编程/32 异常处理.py", line 17, in 
7 name8 NameError: name 'name' is not defined

c、IndexError

1 l = [1, 2, 3]2 l[100]3 4 结果为:5 6 Traceback (most recent call last):7   File "C:/Users/xu516/PycharmProjects/Python全栈开发/第三模块/面向对象编程/32 异常处理.py", line 20, in 
8 l[100]9 IndexError: list index out of range

d、KeyError

1 d = {}2 d['name']3 4 结果为:5 6 Traceback (most recent call last):7   File "C:/Users/xu516/PycharmProjects/Python全栈开发/第三模块/面向对象编程/32 异常处理.py", line 23, in 
8 d['name']9 KeyError: 'name'

e、AttributeError

1 class Foo: 2     pass 3  4 Foo.xxx 5  6 结果为: 7  8 Traceback (most recent call last): 9   File "C:/Users/xu516/PycharmProjects/Python全栈开发/第三模块/面向对象编程/32 异常处理.py", line 28, in 
10 Foo.xxx11 AttributeError: type object 'Foo' has no attribute 'xxx'

f、TypeError

1 for i in 3:2     pass3 4 结果为:5 6 Traceback (most recent call last):7   File "C:/Users/xu516/PycharmProjects/Python全栈开发/第三模块/面向对象编程/32 异常处理.py", line 30, in 
8 for i in 3:9 TypeError: 'int' object is not iterable

g、ZeroDivisionError

1 res1 = 1 / 0 2 res2 = 1 + 'str' 3  4 结果为: 5  6  7 Traceback (most recent call last): 8   File "C:/Users/xu516/PycharmProjects/Python全栈开发/第三模块/面向对象编程/32 异常处理.py", line 33, in 
9 res1 = 1 / 010 ZeroDivisionError: division by zero

h、KeyboardInterrupt

1 >>>2 >>> import time3 >>> time.sleep(1000)4 Traceback (most recent call last):5   File "
", line 1, in
6 KeyboardInterrupt7 >>>

三、异常

强调1:错误发生条件如果是可以预知的,此时应该用if判断方法去预防异常

例如:

1 AGE = 10 2  3 age = input('>>: ').strip() 4 age = int(age) 5 if age > AGE: 6     print('too big') 7  8 结果为: 9 10 >>: aaa11 Traceback (most recent call last):12   File "C:/Users/xu516/PycharmProjects/Python全栈开发/第三模块/面向对象编程/32 异常处理.py", line 47, in 
13 age = int(age)14 ValueError: invalid literal for int() with base 10: 'aaa'

如果输入为非数字就会报错,可以用if判断避免:

1 AGE = 102 3 age = input('>>: ').strip()4 if age.isdigit():5     6     age = int(age)7     if age > AGE:8         print('too big')

这样就避免抛出异常了

强调2:错误发生的条件如果是不可预知的,此时应该用异常处理机制,try......except

例如:

1 f = open('a.txt') 2  3 print(next(f)) 4 print(next(f)) 5 print(next(f)) 6 print(next(f)) 7 print(next(f)) 8 print(next(f)) 9 print(next(f))10 11 f.close()12 13 结果为:14 15 11116 Traceback (most recent call last):17 18 22219 20   File "C:/Users/xu516/PycharmProjects/Python全栈开发/第三模块/面向对象编程/32 异常处理.py", line 60, in 
21 33322 23 print(next(f))24 44425 26 StopIteration27 555

不知道执行到什么时候发生异常,且发生异常时后面的代码不会执行,此时使用try.......except

1 try: 2     f = open('a.txt') 3  4     print(next(f)) 5     print(next(f)) 6     print(next(f)) 7     print(next(f)) 8     print(next(f)) 9     print(next(f))10     print(next(f))11 12     print('after print')13     f.close()14 15 except StopIteration:16     print('出错啦')17 18 结果为:19 20 11121 22 22223 24 33325 26 44427 28 55529 出错啦

在try except 后面的代码还是可以正常执行的,

1 try: 2     f = open('a.txt') 3  4     print(next(f)) 5     print(next(f)) 6     print(next(f)) 7     print(next(f)) 8     print(next(f)) 9     print(next(f))10     print(next(f))11 12     print('after print')13     f.close()14 15 except StopIteration:16     print('出错啦')17 18 print('========1')19 print('========2')20 print('========3')21 22 结果为:23 24 11125 26 22227 28 33329 30 44431 32 55533 出错啦34 ========135 ========236 ========3

 

转载于:https://www.cnblogs.com/xudachen/p/8667225.html

你可能感兴趣的文章
玉伯的一道课后题题解(关于 IEEE 754 双精度浮点型精度损失)
查看>>
《BI那点儿事》数据流转换——百分比抽样、行抽样
查看>>
哈希(1) hash的基本知识回顾
查看>>
Leetcode 6——ZigZag Conversion
查看>>
dockerfile_nginx+PHP+mongo数据库_完美搭建
查看>>
Http协议的学习
查看>>
【转】轻松记住大端小端的含义(附对大端和小端的解释)
查看>>
设计模式那点事读书笔记(3)----建造者模式
查看>>
ActiveMQ学习笔记(1)----初识ActiveMQ
查看>>
Java与算法之(2) - 快速排序
查看>>
Windows之IOCP
查看>>
机器学习降维之主成分分析
查看>>
WebSocket & websockets
查看>>
openssl 升级
查看>>
ASP.NET MVC:通过 FileResult 向 浏览器 发送文件
查看>>
CVE-2010-2883Adobe Reader和Acrobat CoolType.dll栈缓冲区溢出漏洞分析
查看>>
使用正确的姿势跨域
查看>>
AccountManager教程
查看>>
Android学习笔记(十一)——从意图返回结果
查看>>
算法导论笔记(四)算法分析常用符号
查看>>