在最后一行中,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'
答案 0 :(得分:4)
当您这样做:
except insufficient as i:
Exception
块中的代码抛出的任何try
都分配给变量i
,并在except
块中可用。因此,如果您的try
块引发insufficient
异常,则该异常将分配给i
。因此,您可以参考i.msg
。
但是由于msg
是类insufficient
中的对象属性,所以insufficient.msg
的计算结果为空。
最后:
except insufficient:
在except
块中不使抛出的对象可用。 insufficient
这里仅仅是类型标识符。因此,您无法访问msg
属性。