Python3之异常处理

不管哪种语言,程序都会出现异常。我们就需要对它进行处理。菜鸟教程详细对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

对的,这才是我想要的结果

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值