Search code examples
pythonexceptiontry-exceptctf

Why do TextError exceptions not function properly in this code?


The code below output's "Do not divide by zero, that is forbidden" fine when the user inputs zero, however if a sentence or characters are entered it returns a ValueError. The error is as follows:

Traceback (most recent call last):
  File "exceptions.py", line 5, in <module>
    num2 = int(input())
ValueError: invalid literal for int() with base 10: 'Hello World'

The code is from PicoCTF's tutorial section and can be found below:

I have tried changing: except TypeError: print("Your input value must be an integer.")

to

except Value Error: print("Your input value must be an integer.")

num1 = 8
print("Input the number that will divide:")
num2 = int(input())
try:
    result = num1 / num2
    print(result)
except ZeroDivisionError:
    print("Do not divide by zero, that is forbidden.")
except TypeError:
    print("Your input value must be an integer.")
print("The program keeps executing to do other stuff...")

however it still does not output the exception I have entered. Am I missing something? For reference I am using picoCTF's internal web shell Thank you all in advance for your support.


Solution

  • The ValueError occurs at the int(...) call. If you want to handle it, you need to add a try: block around that code. For example:

    num1 = 8
    print("Input the number that will divide:")
    num2_str = input()
    try:
        num2 = int(num2_str)
    except ValueError:
        print(f"this isn't an integer: {num_str}")
        num2 = 0 # or whatever you want the default to be
    
    try:
        result = num1 / num2
        print(result)
    except ZeroDivisionError:
        print("Do not divide by zero, that is forbidden.")
    except TypeError:
        print("Your input value must be an integer.")
    print("The program keeps executing to do other stuff...")