How do i create two exceptions to the same type of error?

Viewed 65

for example, on this code, there are two possibilities of value errors, delta can be negative or the variables can be strings. But i cant specify if its the delta error or the string variables error

import math


a = input('Input the value of A')
b = input('Input the value of B')
c = input('Input the value of  C')
delta = int(b) ** 2 - 4 * int(a) * int(c)

try:
    x1 = (int(-b) + math.sqrt(delta)) / 2 * int(a)
    x2 = (int(-b) - math.sqrt(delta)) / 2 * int(a)
    print('x1 is equal to : ', str(x1))
    print('x2 is equal to : ', str(x2))
except ValueError:
    print('Delta is negative, it is not possible to calculate X')
except ValueError:
    print('Variables must be numbers')

when i set the variables as strings i get this message

ValueError: invalid literal for int() with base 10: 's'
1 Answers

Do you mean something like this?:

from sys import exc_info
# https://docs.python.org/3/library/sys.html

try:
    # raise …
except ValueError:
    if exc_info()[1].startswith("invalid literal for int"):
        # do one thing
    elif:
        # do something else

# or
try:
    # raise …
except ValueError as e:
    if e.value.startswith("invalid literal for int"):
        # …
    elif:
        # …
Related