我在例外处理中有一个例外吗?

时间:2019-05-26 18:20:29

标签: python

在最后一行中,i通过使用别名打印邮件时运行得很好,例如

except insufficient as i :
    print("exception is caught",i.msg)

但是当我这样做

except insufficient :
    print("exception is caught",insufficient.msg)

这是一个错误..为什么???

```class insufficient(ZeroDivisionError):
    def __init__(self,arg):
            self.msg=arg
balance=5000
w=int(input("enter a number"))
try:
    if w>5000:
        raise insufficient("balance in the account is insufficient")
    balance=balance-w
    print("no exception and balance is=",balance)
except insufficient :
    print("exception is caught",insufficient.msg)```

错误日志:-

Traceback (most recent call last):
  File "C:\Users\ahmod\AppData\Local\Programs\Python\Python37-32\hello.py", line 8, in <module>
    raise insufficient("balance in the account is insufficient")
insufficient: balance in the account is insufficient

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\ahmod\AppData\Local\Programs\Python\Python37-32\hello.py", line 12, in <module>
    print("exception is caught",insufficient.msg)
AttributeError: type object 'insufficient' has no attribute 'msg'

1 个答案:

答案 0 :(得分:4)

当您这样做:

except insufficient as i:

Exception块中的代码抛出的任何try都分配给变量i,并在except块中可用。因此,如果您的try块引发insufficient异常,则该异常将分配给i。因此,您可以参考i.msg

但是由于msg是类insufficient中的对象属性,所以insufficient.msg的计算结果为空。

最后:

except insufficient:

except块中不使抛出的对象可用。 insufficient这里仅仅是类型标识符。因此,您无法访问msg属性。