不管哪种语言,程序都会出现异常。我们就需要对它进行处理。菜鸟教程详细对try except进行了说明
https://www.runoob.com/python3/python3-errors-execptions.html
代码:
try:
a = [1, 2, 3, 4]
print(a[10])
except Exception as e:
print("数组越界")
finally:
print("我肯定要执行")
执行结果:
数组越界
我肯定要执行
Process finished with exit code 0
这时我们发现不能准确定位到报错代码行数以及异常类型。这时我们打印出e看看
代码:
try:
a = [1, 2, 3, 4]
print(a[10])
except Exception as e:
print(e)
print("数组越界")
finally:
print("我肯定要执行")
结果:
list index out of range
数组越界
我肯定要执行
Process finished with exit code 0
这里我们看到,异常类型抛出了但是没定位到代码行号。
网上查询,有人说可以用e.value、e.message。执行情况如下:
try:
a = [1, 2, 3, 4]
print(a[10])
except Exception as e:
print(e)
print(e.message)
print("数组越界")
finally:
print("我肯定要执行")
执行结果:
我肯定要执行
File "/Users/xxx/python/pym/learning/cainiao.py", line 11, in <module>
print(a[10])
IndexError: list index out of range
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/Users/xxx/python/pym/learning/cainiao.py", line 14, in <module>
print(e.message)
AttributeError: 'IndexError' object has no attribute 'message'
Process finished with exit code 1
try:
a = [1, 2, 3, 4]
print(a[10])
except Exception as e:
print(e)
print(e.value)
print("数组越界")
finally:
print("我肯定要执行")
执行结果:
Traceback (most recent call last):
File "/Users/xxx/python/pym/learning/cainiao.py", line 11, in <module>
print(a[10])
IndexError: list index out of range
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/Users/xxx/python/pym/learning/cainiao.py", line 14, in <module>
print(e.value)
list index out of range
AttributeError: 'IndexError' object has no attribute 'value'
我肯定要执行
Process finished with exit code 1
这时发现,行号以及异常都抛出。但是捕获代码抛出了异常。再次百度
导入traceback包
import traceback
try:
a = [1, 2, 3, 4]
print(a[10])
except Exception as e:
print(e)
#添加的这行代码
print(traceback.format_exc())
print("数组越界")
finally:
print("我肯定要执行")
结果:
list index out of range
Traceback (most recent call last):
File "/Users/xxx/python/pym/learning/cainiao.py", line 12, in <module>
print(a[10])
IndexError: list index out of range
数组越界
我肯定要执行
Process finished with exit code 0
对的,这才是我想要的结果