python_捕获异常

python捕获分类:

1、明确类型进行捕获

d={"a":1}
try:
    d["key"]
except KeyError as e: #只能捕获keyerror这一种错误
   print('出错了')
try:
    1/0
    d['key']
except ZeroDivisionError as e: #捕获ZeroDivisionError这一种错误
    print("error")


C:\Users\zhaow\AppData\Local\Programs\Python\Python37\python.exe D:/study/python/test/dd.py
error
d={"a":1}
try:  #当try中有多个错误是,根据位置在前的错误会报错走捕获,后面的错误捕获不再进行输出
    d['key']
    1/0
except ZeroDivisionError as e: #捕获ZeroDivisionError这一种错误
    print("error")
except KeyError as e: #只能捕获keyerror这一种错误
   print('出错了')

C:\Users\zhaow\AppData\Local\Programs\Python\Python37\python.exe D:/study/python/test/dd.py
出错了  #因为keyerror的错误在前,所以程序走了其捕获异常代码,未走获ZeroDivisionError这个捕获

2、未明确类型进行统一捕获

try:
    1/0
except KeyError as e:  #只能捕获一种错误
    print("error")


C:\Users\zhaow\AppData\Local\Programs\Python\Python37\python.exe D:/study/python/test/dd.py
Traceback (most recent call last):
  File "D:/study/python/test/dd.py", line 89, in <module>
    1/0
ZeroDivisionError: division by zero
try:
    1/0
except Exception as e:  #捕获任何错误
    print("error")

C:\Users\zhaow\AppData\Local\Programs\Python\Python37\python.exe D:/study/python/test/dd.py
error
try:
    d[9]
except Exception as e:  #捕获任何错误
    print('error')

C:\Users\zhaow\AppData\Local\Programs\Python\Python37\python.exe D:/study/python/test/dd.py
error

3、捕获错误带分支逻辑

try:
    a='000'
except Exception as e:  #当有错误运行这里的代码
    print('error')
else: #当没有捕获到错误就运行这里的代码
    print('无错误走这里')

C:\Users\zhaow\AppData\Local\Programs\Python\Python37\python.exe D:/study/python/test/dd.py
无错误走这里
try:
    a=b
except Exception as e:  #当有错误运行这里的代码
    print('有错误运行这里')
else: #当没有捕获到错误就运行这里的代码
    print('无错误走这里')

C:\Users\zhaow\AppData\Local\Programs\Python\Python37\python.exe D:/study/python/test/dd.py
有错误运行这里

 4、捕获带finally

try:
    a=b
except Exception as e:  #当有错误运行这里的代码
    print('有错误运行这里')
else: #当没有捕获到错误就运行这里的代码
    print('无错误走这里')
finally: #出错还是不出错程序都会运行这里的代码
    print('出错还是不出错我肯定是要运行的')

C:\Users\zhaow\AppData\Local\Programs\Python\Python37\python.exe D:/study/python/test/dd.py
有错误运行这里
出错还是不出错我肯定是要运行的
try:
    a=1
except Exception as e:  #当有错误运行这里的代码
    print('有错误运行这里')
else: #当没有捕获到错误就运行这里的代码
    print('无错误走这里')
finally: #出错还是不出错程序都会运行这里的代码
    print('出错还是不出错我肯定是要运行的')

C:\Users\zhaow\AppData\Local\Programs\Python\Python37\python.exe D:/study/python/test/dd.py
无错误走这里
出错还是不出错我肯定是要运行的

 5、异常的输出

import traceback
try:
    a=a
except Exception as e:
    print(e) #输出具体的错误内容
print('=====================')
try:
    a=a
except Exception as e:
    print(traceback.format_exc()) #输出详细的错误内容

C:\Users\zhaow\AppData\Local\Programs\Python\Python37\python.exe D:/study/python/test/dd.py
name 'a' is not defined
=====================
Traceback (most recent call last):
  File "D:/study/python/test/dd.py", line 94, in <module>
    a=a
NameError: name 'a' is not defined

 

 

posted @ 2019-07-10 16:23  小戳同学  阅读(282)  评论(0编辑  收藏  举报