[英]IF and ELSE Exception in Python3
I am trying to catch an exception for two boolean (for if and else separately). 我正在尝试捕获两个布尔值(对于if和else分别)的异常。
this is what I am working on: 这就是我正在从事的工作:
from math import *
from decimal import Decimal
def add(self, *args):
try:
if all(isinstance(n, int) for n in args):
print(sum(int(n) for n in args))
else:
print(fsum(Decimal(n) for n in args))
except (NameError, SyntaxError) as e:
print("Error! {}".format(e))
def main():
add(a)
if __name__ == '__main__': main()
Both if and else gives me two exceptions NameError
and SyntaxError
, if I give add(a)
its giving me NameError
as the exception. if和else都给我两个异常
NameError
和SyntaxError
,如果我给它的add(a)
给我NameError
作为异常。 But the except
is not catching the error. 但是
except
是没有捕获错误。
How should I catch the exception for both of them separately? 我应该如何分别捕获它们的异常?
From what I understand I think you can try like this. 据我了解,我认为您可以尝试这样。
except NameError as e :
print "Name error occured"
print("Error! {}".format(e))
except SyntaxError as f:
print "Syntax error occurred"
print("Error! {}".format(f))
Ok, person who gave me -1, just to let you know that it was an honest mistake and i am new to python. 好吧,给我-1的人,只是想告诉你这是一个诚实的错误,我是python的新手。 keeping that aside.
放在一边。
so just got to know that SyntaxError
are thrown at compile time which cannot be caught at run time that is what -> [ SyntaxError not excepting in Python 3 says 所以只知道
SyntaxError
是在编译时抛出的,因此在运行时无法捕获-> [ SyntaxError并非在Python 3中除外
so I figured it and thanks to @thefourtheye 所以我想通了,感谢@thefourtheye
from math import *
from decimal import Decimal
def add(*args):
if all(isinstance(n, int) for n in args):
print(sum(int(n) for n in args))
else:
print(fsum(Decimal(n) for n in args))
def main():
try:
add(dfvdv)
except NameError:
print("Error!")
if __name__ == '__main__': main()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.