1 异常处理
使用try语句进行处理异常。一般形式如下:
try:
<要进行捕捉异常的语句>
except <异常语句>:
<对异常进行处理的语句>
except <异常语句>:
<对异常进行处理的语句>
else:
<未发生异常执行的语句>
例1
l=[1,2,3,4]
try:
l[7]
except:#未填写异常名则表示捕获所有异常
print('error')
else:
print('no error')
error
'''#不进行异常处理则是:
l[7]
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/IPython/core/interactiveshell.py", line 2910, in run_code
exec(code_obj, self.user_global_ns, self.user_ns)
File "<ipython-input-4-dc61b3a869da>", line 1, in <module>
l[7]
IndexError: list index out of range
'''
多重捕获异常:在python中可以使用try语句嵌套另一个try语句,由于python将try语句放在堆栈中,因此一旦发生异常,python将匹配最近的except语句,如果except能处理次异常,则外围的except语句将不会捕获异常,如果忽略此异常,则该异常将被外围try捕获。
try:
try:
l[8]
except:
print('error1')
except:
print('error2')
else:
print('ok')
error1
ok
'''
使用except捕获零除异常,实际非零除异常
try:
try:
l[8]
except ZeroDivisionError:
print('error1')
except:
print('error2')
else:
print('ok')
error2
'''
2 调试
使用runeval调试,使用n命令单步执行
import pdb
pdb.runeval('l[1]')
> <string>(1)<module>()
(Pdb) >? n
--Return--
> <string>(1)<module>()->2
(Pdb) >? n
Out[8]: 2