异常执行路径
try:
text = input('请输入 --> ')
except EOFError:
print('为什么你按下了EOF?')
except KeyboardInterrupt:
print('你取消了操作')
except Exception as e: # 当前面的异常都没匹配到,万能异常
print(e)
else:
print('你输入了 {}'.format(text))
finally:
print("程序结束...")
try–>代码报错–>except–>finally
try–>代码正常–>else ->finally
常见异常模拟
- 直观体验
>>> a
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'a' is not defined
>>> d={}
>>> d['name']
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'name'
>>>
>>> arr=[]
>>> arr[2]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list index out of range
>>> int(a)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'a' is not defined
>>> int('a')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: 'a'
###################################
- IndexError
d = ["mao", 'tai']
try:
d[10]
except IndexError, e:
print e
###################################
- KeyError
d = {'k1':'v1'}
try:
d['k20']
except KeyError, e:
print e
###################################
- ValueError
s1 = 'hello'
try:
int(s1)
except ValueError, e:
print e
###################################
异常 | 原因 |
---|---|
AttributeError | 赋值失败: 试图访问一个对象没有的属性,比如foo.x,但是foo没有属性x |
IOError | 文件操作失败: 输入/输出异常;基本上是无法打开文件 |
ImportError | 导入失败: 无法引入模块或包;基本上是路径问题或名称错误 |
IndentationError | 缩进错误: 语法错误(的子类) ;代码没有正确对齐 |
IndexError | 下标越界: 比如当x只有三个元素,却试图访问x[5] |
KeyError | 字段k错误: 字典里k不存在 |
KeyboardInterrupt | Ctrl+c被按下 |
EOFError | Ctrl+d被按下 |
NameError | 变量不存在: 使用一个还未被赋予对象的变量 |
SyntaxError | 代码形式错误 |
TypeError | 对象类型错误: 传入对象类型与要求的不符合 |
ValueError | 对象的值错误: 传入一个调用者不期望的值,即使值的类型是正确的 |
UnboundLocalError | 试图访问一个还未被设置的局部变量,基本上是由于另有一个同名的全局变量,导致你以为正在访问它 |
异常应用
- 输入的必须是数字
- 输入的必须是y 或 n
- 输入几次机会
- 要求输入一个数字
while True:
try:
num = raw_input("input a int num: ")
num = int(num)
except ValueError:
print "pls enter a int num"
- 要求输入的值在y 或 n之间
while True:
try:
op = raw_input("y/n >")
op = op.lower()
if op in ['y','n']:
print "input correct"
except Exception as e:
print "pls input y or n"
- 程序启动后,提示输入, 仅输出n/N或nxx程序结束
while True:
try:
op = raw_input("Again?[y] > ")
op = op.lower()
if op and op[0]=="n":
break
except(KeyboardInterrupt,EOFError):
print("pls input a y/n")
- 猜一个数字,如果和内置的值相等,则退出,最多3次猜测机会.
直接回车,不算浪费机会
ctrl+c无法退出
输入的必须是数字,如果不是数字则报错
已上这三种异常均需要扑捉并提示try again
count = 1
while True:
try:
if (int(input("guess a num > "))) == 100:
print("correct")
break
if count == 3:
print("th coreect count is 100")
break
else:
print("try again")
count += 1
except(KeyboardInterrupt, IOError, ValueError):
print "pls input a count"