1

I'm making a simple calculator program for a class project. I have an Exception handler that catches errors and returns the error type. Though whenever it catches an Exception, it prints the error type along with its description. Is there a way to only have it print the error type?

Code:

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()
            

For x or n, it only accepts 1, 2, 3, or 4 as input. Say for example, I were to input t for x. This would raise a ValueError. The try except statement inside the while loop then catches said ValueError and prints out Error caught: type(error).

Desired Output:

>>> t
Error caught: ValueError

Given output:

>>> t
Error caught: <class 'ValueError'> (if type(e))

or:

>>> t
Error caught: ValueError: insert error description (if repr(e))

How do I get the desired output?

Galaxiias
  • 49
  • 4

1 Answers1

1

You can print the caught Exception's type name like this:

except Exception as e:
    print('Error caught:', type(e).__name__)
martineau
  • 99,260
  • 22
  • 139
  • 249