如果不加异常处理
def test(input):
# try:
print("1: {}".format(input))
raise OSError
print("2222") # 是不会执行到的
#
# except Exception as err:
# print(err)
if __name__ == '__main__':
input = "hello"
test(input)
print("fixed error")
报错信息
1: hello
Traceback (most recent call last):
File "/Users/.../异常处理.py", line 13, in <module>
test(input)
File "/Users/.../异常处理.py", line 5, in test
raise OSError
OSError
加了异常处理以后
def test(input):
try:
print("1: {}".format(input))
raise OSError
print("2222") ## 不会运行到的
except Exception as err:
print("get err:{}".format(err))
if __name__ == '__main__':
input = "hello"
test(input) # 忽略这个函数内部的异常
print("fixed error") # 可以处理之后的打印信息
正常打印信息
1: hello
get err:
fixed error