四、异常处理:
(1)捕获所有异常
try:
<语句>
except:
print('异常说明')
try:
<语句>
except (<异常名1>, <异常名2>, ...):
print('异常说明')
try:
<语句>
except <异常名1>:
print('异常说明1')
except <异常名2>:
print('异常说明2')
(2)捕获指定异常
try:
<语句>
except <异常名>:
print('异常说明')
(3)万能捕获异常
try:
<语句>
except Exception as e:
print('报的就是这个错:', e)
try:
f = open("file-not-exists", "r")
except IOError as e:
print("open exception: %s: %s" %(e.errno, e.strerror))
(4)具有优先级异常
try:
<语句>
except IndexError as e:
print(e)
except KeyError as e:
print(e)
else:
print('try内没有异常执行')
finally:
print('无论是否异常,都会执行')
(5)raise自定义异常
def func(n):
try:
if n == 0:
raise ValueError('传入参数错误')
return n
except Exception as e:
print(e)
func(0)
(6)详细报错,也会指出哪一行出的错
import traceback
try:
1 / 0
except Exception as e:
traceback.print_exc()
traceback.print_exc() 与 traceback.format_exc():format_exc()返回字符串,print_exc()则直接给打印出来
print_exc()可接收file参数写入到一个文件:traceback.print_exc(file=open('a.txt','w+'))
标签:exc,处理,traceback,except,try,py04,print,异常
From: https://www.cnblogs.com/wangfengzi/p/17858967.html