Kevical
Kevical

Reputation: 1

Why is my exception getting printed twice?

The following code looks good to me, but when I use e0 with my except ValueError it prints twice, please help my slow brain

my inputs are 20.5 and 5

try:
    user_num = int(input())
    div_num = int(input())
    print(user_num / div_num)
except ValueError as e0:
    print('Input Exception: invalid literal for int() with base 10:', e0)
except ZeroDivisionError:
    print('Zero Division Exception: integer division or modulo by zero')

Output

Input Exception: invalid literal for int() with base 10: invalid literal for int() with base 10: '20.5'

Tried to remove e0, print my entire statement without e0, perfectly prints, but I cannot put the e0 otherwise it just prints the output twice for some reason.

Upvotes: 0

Views: 242

Answers (3)

igr2020
igr2020

Reputation: 3

the raised error (e0) includes "invalid literal for int() with base 10: '20.5'" a fix would be-

try:
    user_num = int(input())
    div_num = int(input())
    print(user_num / div_num)
except ValueError as e0:
    print(e0)
except ZeroDivisionError:
    print('Zero Division Exception: integer division or modulo by zero')

Upvotes: 0

Ghorban M. Tavakoly
Ghorban M. Tavakoly

Reputation: 1249

By running the following code, it is easy to understand the problem:

>>> int("20.5")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '20.5'

the raised exception's message is the exact message you want to print. So you can just print the e0 without leading string.

I prefer this:

try:
    user_num = int(input())
    div_num = int(input())
    print(user_num / div_num)
except (ValueError, ZeroDivisionError) as e:
    print(e)

Upvotes: 3

user2357112
user2357112

Reputation: 281757

e0 is not the string you tried to convert. e0 is the exception object. Printing that prints the exception's message, and the exception's message is "invalid literal for int() with base 10: '20.5'".

"invalid literal for int() with base 10:" shows up twice in the output because you're printing it manually, and also printing an exception message with that text in it.

Upvotes: 2

Related Questions