Search code examples
pythonvalueerrorexcept

Python exception handling ValueError


Why does the except ValueError as ve block does not get executed , when I pass a character?

class Division :
    def divide(numerator, denominator):
        try:
            print(f"Result  : {(numerator/denominator)}")
        except ValueError as ve:
            print("Invalid input given",ve)
        except Exception as e :
            print(f"Exception caught : {e} ")

    if __name__ == "__main__" :
        a = int(input("Enter the numerator - "))
        b = int(input("Enter the denominator - "))
        divide(a,b)

O/P:

Enter the numerator - A
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 10, in Division
ValueError: invalid literal for int() with base 10: 'A'

Instead I want to see print("Invalid input given",ve) getting executed.


Solution

  • If you look at the trace information in your error, the exception is not being thrown by your divide function. If you use the code below to collect the user input without casting, you can avoid throwing this exception outside of your divide function.

    if __name__ == "__main__" :
        a = input("Enter the numerator - ")
        b = input("Enter the denominator - ")
        divide(a,b)
    

    As Karl pointed out in the comment, you will need to cast the values to int inside your divide function instead to generate the ValueError there. Otherwise, it will throw a TypeError.