Python程序设计教程课件-第九章异常 课件(共49张PPT)

资源下载
  1. 二一教育资源

Python程序设计教程课件-第九章异常 课件(共49张PPT)

资源简介

(共49张PPT)
第9章 异常
Chap9 Exceptions
There is a road in the mountains of books, and diligence is the path
python中的异常
9.1
2
程序设计错误
3
语法错误
运行时错误
逻辑错误
6 = x * 2
x = 3 / 0
area = 2 * 3.14 * 3
4
异常(Exception)
Traceback (most recent call last):
File "", line 1, in
1/0
ZeroDivisionError: division by zero
5
>>> 1 / 0
Source
Traceback (most recent call last):
File "", line 1, in
y = x + 1
NameError: name 'x' is not defined
>>> y = x + 1
Source
用异常对象(exception object)表示异常情况
Python用异常对象(exception object)表示异常情况,遇到错误时如果异常对象没有
6
异常
查看异常类 dir(__builtins__)
7
类 名 描 述
BaseException 所有异常的基类
Exception 常规异常的基类
AttributeError 对象不存在此属性
IndexError 序列中无此索引
IOError 输入/输出操作失败
KeyboardInterrupt 用户中断执行(通常输入Ctr-C)
KeyError 映射中不存在此键
NameError 找不到名字(变量)
SyntaxError Python 语法错误
TypeError 对类型无效的操作
ValueError 传入无效的参数
ZeroDivisionError 除(或取模)运算的第二个参数为0
异常处理
if y != 0:
print(x / y)
else:
print('division by zero')
8
VS
try-except
异常处理语句
可以用if语句判断除数的特殊情况后单独处理,形如:
但这种做法不够灵活,有时效率也不高。Python中提供了简单自然的异常处理方法。因为这些实例可以被引发、捕捉,对捕捉到的异常可以进行处理,以免程序因为异常而终止运行。
捕捉异常
9.2
9
异常
Enter the first number: a
Traceback (most recent call last):
File "C:\Python\programs\exception1.py", line 1, in
num1 = int(input('Enter the first number: '))
ValueError: invalid literal for int() with base 10: 'a'
10
# Filename: prog9-1.py
num1 = int(input('Enter the first number: '))
num2 = int(input('Enter the second number: '))
print(num1 / num2)
File
9.2.1 try-except语句
11
12
try-except语句
13
# Filename: prog9-2.py
try:
num1 = int(input('Enter the first number: '))
num2 = int(input('Enter the second number: '))
print(num1 / num2)
except ValueError:
print('Please input a digit!')
File
try:
被检测的语句块
except Exception:
异常处理语句块
14
try-except语句
15
# Filename: prog9-3.py
try:
num1 = int(input('Enter the first number: '))
num2 = int(input('Enter the second number: '))
print(num1 / num2)
except ZeroDivisionError:
print('The second number cannot be zero!')
File
16
9.2.2 多个except子句和一个except块捕捉多个异常
17
多个except子句
18
# Filename: prog9-4.py
try:
num1 = int(input('Enter the first number: '))
num2 = int(input('Enter the second number: '))
print(num1 / num2)
except ValueError:
print('Please input a digit!')
except ZeroDivisionError:
print('The second number cannot be zero!')
File
一个except块捕捉多个异常
19
# Filename: prog9-5.py
try:
num1 = int(input('Enter the first number: '))
num2 = int(input('Enter the second number: '))
print(num1 / num2)
except (ValueError, ZeroDivisionError):
print('Invalid input!')
File
空except子句
20
# Filename: prog9-6.py
try:
num1 = int(input('Enter the first number: '))
num2 = int(input('Enter the second number: '))
print(num1 / num2)
except:
print('Something went wrong!')
File
一了百了:except:
如果想要捕捉所有的异常,可以使用空的except子句
21
as子句
22
# Filename: prog9-7.py
try:
num1 = int(input('Enter the first number: '))
num2 = int(input('Enter the second number: '))
print(num1 / num2)
except Exception as err:
print('Something went wrong!')
print(err)
File
23
as子句
24
try:
被检测的语句块
except 异常类名 as 错误原因名:
异常处理语句块
print(错误原因名)
9.2.3 else子句
25
else子句
26
# Filename: prog9-8.py
try:
num1 = int(input('Enter the first number: '))
num2 = int(input('Enter the second number: '))
print(num1 / num2)
except(ValueError, ZeroDivisionError):
print('Invalid input!')
else:
print('Aha, I am smart.')
File
Enter the first number: 3
Enter the second number: 5
0.6
Aha, I am smart.
如果输入正确没有引发异常,则跳过except执行else子句
程序prog9-2~prog9-8 中虽然都做了异常处理,但只有简单的提示信息不能再次输人,如果想要在产生异常后能多次输入直到正确为止,则可以在外层加上while True语句和else子句。
27
加入循环
28
# Filename: prog9-9.py
while True:
try:
num1 = int(input('Enter the first number: '))
num2 = int(input('Enter the second number: '))
print(num1 / num2)
except ValueError:
print('Please input a digit!')
except ZeroDivisionError:
print('The second number cannot be zero!')
else:
break
File
Enter the first number: a
Please input a digit!
Enter the first number: 3
Enter the second number: 0
The second number cannot be zero!
Enter the first number: 3
Enter the second number: 5
0.6
29
break语句的位置
30
# Filename: prog9-9’.py
while True:
try:
num1 = int(input('Enter the first number: '))
num2 = int(input('Enter the second number: '))
print(num1 / num2)
break
except ValueError:
print('Please input a digit!')
except ZeroDivisionError:
print('The second number cannot be zero!')
File
改写prog9-9.py
break语句的位置
31
# Filename: prog9-11.py
while True:
try:
num1 = int(input('Enter the first number: '))
num2 = int(input('Enter the second number: '))
print(num1 / num2)
break
except Exception as err:
print(err)
File
break语句的位置并非固定放在else子句中,有时也会放在except子句中,完全根据需要而定。例如,prog9-10可以改写成如下形式:
32
break语句的位置
33
# Filename: prog9-12.py
aList = [1, 2, 3, 4, 5]
i = 0
while True:
try:
print(aList[i])
except IndexError:
print('index error')
break
else:
i += 1
File
9.2.4 finally子句
34
finally子句可以用在try语句中,无论是否发生异常, finally子句中的语句块都要被执行。观察下面的程序及其输入和输出结果。
35
finally子句
36
# Filename: prog9-13.py
def finallyTest():
try:
x = int(input('Enter the first number: '))
y = int(input('Enter the second number: '))
print(x / y)
return 1
except Exception as err:
print(err)
return 0
finally:
print('It is a finally clause.')
result = finallyTest()
print(result)
File
Enter the first number: 3
Enter the second number: 5
0.6
It is a finally clause.
1
Enter the first number: 3
Enter the second number: 0
division by zero
It is a finally clause.
0
37
38
39
9.3
上下文管理器和with语句
40
41
上下文管理器(Context Manager)和with语句
42
# Filename: prog9-14.py
try:
f = open('data.txt')
for line in f:
print(line, end = '')
except IOError:
print('Cannot open the file!')
finally:
f.close()
File
43
上下文管理器(Context Manager)和with语句
44
# Filename: prog9-15.py
with open('data.txt') as f:
for line in f:
print(line, end='')
File
上下文管理器
定义和控制代码块执行前的准备动作及执行后的收尾动作
通过with语句在支持上下文管理协议的对象(如文件对象)上方便地进行使用
with 上下文管理表达式 as 变量:
语句序列
程序prog9-15首先打开当前目录下的data. txt文件并将创建的文件对象赋给变量f,执行with语句的for循环将文件中的内容按行输出,如果文件不存在,则会产生FileNot-FoundError异常。with语句在文件结束后会自动关闭文件,因此不再需要close()方法。相比 try-finally语句, with语句更精简和健壮,所以是Python中操作文件和数据库等对象时的推荐用法。
45
小结
9.4
46
小结
47
48
49

展开更多......

收起↑

资源预览