我正在为一个班级项目编写一个简单的计算器程序。我有一个捕获错误并返回错误type
的Exception
处理程序。尽管每当捕获到Exception
时,它都会打印错误type
及其描述。有没有办法只打印错误type
?
代码:
operations = ('Add', 'Subtract', 'Multiply', 'Divide')
def insigStrip(flt):
if str(flt)[-1] == '0':
return int(flt)
return flt
def main():
print('Select operation:')
for i in range(len(operations)):
print(str(i+1) + ':', operations[i])
while True:
try:
option = int(input('Enter choice(1/2/3/4): '))
if option in range(len(operations) + 1):
x = insigStrip(float(input('Enter first number: ')))
n = insigStrip(float(input('Enter second number: ')))
if option == 1:
print(x, '+', n, '=', insigStrip(x+n))
if option == 2:
print(x, '-', n, '=', insigStrip(x-n))
if option == 3:
print(x, '*', n, '=', insigStrip(x*n))
if option == 4:
try:
print(x, '/', n, '=', insigStrip(x/n))
except ZeroDivisionError:
print('Cannot divide by Zero.')
break
else:
print('Invalid input.')
continue
except Exception as e:
print('Error caught:', repr(e))
if __name__ == '__main__':
main()
对于x
或n
,它只接受1、2、3或4作为输入。例如,我要为x
输入t。这将引发ValueError
。然后,while
循环中的try except
语句捕获上述ValueError
并打印出Error caught: type(error)
。
所需输出:
>>> t
Error caught: ValueError
给定输出:
>>> t
Error caught: <class 'ValueError'> (if type(e))
或:
>>> t
Error caught: ValueError: insert error description (if repr(e))
我如何得到想要的输出?
可以打印捕获的Exception
的类型name这样的:
except Exception as e:
print('Error caught:', type(e).__name__)