打印捕获的异常类型而不打印错误描述

Print caught Exception type without printing the error description

我正在为 class 项目制作一个简单的计算器程序。我有一个 Exception 捕获错误的处理程序和 returns 错误 type。尽管每当它捕获到 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()
            

对于xn,它只接受1、2、3或4作为输入。比方说,我要为 x 输入 t。这将引发 ValueErrorwhile 循环中的 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__)