内容正文:
第9章 异常
Chap9 Exceptions
Nanjing University
1
Python中的异常
9.1
2
Python
Nanjing University
程序设计错误
3
语法错误
运行时错误
逻辑错误
6 = x * 2
x = 3 / 0
area = 2 * 3.14 * 3
Python
Nanjing University
3
4
Python
Nanjing University
异常(Exception)
Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
1/0
ZeroDivisionError: division by zero
5
>>> 1 / 0
Source
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
y = x + 1
NameError: name 'x' is not defined
>>> y = x + 1
Source
用异常对象(exception object)表示异常情况
Python
Nanjing University
5
Python用异常对象(exception object)表示异常情况,遇到错误时如果异常对象没有
6
Python
Nanjing University
异常
查看异常类 dir(__builtins__)
7
类 名 描 述
BaseException 所有异常的基类
Exception 常规异常的基类
AttributeError 对象不存在此属性
IndexError 序列中无此索引
IOError 输入/输出操作失败
KeyboardInterrupt 用户中断执行(通常输入Ctr-C)
KeyError 映射中不存在此键
NameError 找不到名字(变量)
SyntaxError Python 语法错误
TypeError 对类型无效的操作
ValueError 传入无效的参数
ZeroDivisionError 除(或取模)运算的第二个参数为0
Python
Nanjing University
7
异常处理
if y != 0:
print(x / y)
else:
print('division by zero')
8
VS
try-except
异常处理语句
可以用if语句判断除数的特殊情况后单独处理,形如:
但这种做法不够灵活,有时效率也不高。Python中提供了简单自然的异常处理方法。因为这些实例可以被引发、捕捉,对捕捉到的异常可以进行处理,以免程序因为异常而终止运行。
Python
Nanjing University
8
捕捉异常
9.2
9
Python
Nanjing University
异常
Enter the first number: a
Traceback (most recent call last):
File "C:\Python\programs\exception1.py", line 1, in <module>
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
Python
Nanjing University
9.2.1 try-except语句
11
Python
Nanjing University
12
Python
Nanjing University
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: