主要是用来记录一下: raise Error的用法, 这里我自己引发一个TimeoutError, 这个错误网络爬虫上比较多见, 常常死连不动没任何反应. 这时要事先设置好timeout再连.
import sys
import traceback
def MyTryCatchException():
for i in range(0,3):
try:
if i == 0:
raise TimeoutError('我引发一个超时错误')
elif i == 1:
a = b = c = 1
print (10 /(a+b-2*c)) # 除0错误
elif i == 2:
with open('adsfjowr.xxdf','r',encoding='utf-8') as f: # 打开一个不存在的文件
txt = f.read('hello')
except Exception as e:
if e.__class__ == TimeoutError:
msg = e.args[0]
exc_type, exc_value, exc_traceback_obj = sys.exc_info()
traceback.print_tb(exc_traceback_obj)
elif e.__class__ == ZeroDivisionError:
print(f'发生除零错误 msg:{e.args[0]}')
else:
print( e.__class__ )
print(f'错误 msg:{e.args[1]} { e.filename } ')
if __name__ == "__main__":
MyTryCatchException()