-1

i'm just learning programming and also my native language is not English . so i'm sorry for any vocabulary or grammar issues . i'm trying to create a function that does the try/except scenario but in one function with one argument which in this example is user input . but user input will execute before going into my function so i don't know how to solve it .

i would be appreciated if someone help me with it . thanks in advance.

import time
import sys


def err_handling(command):
    try:
        x = command
    except Exception as e:
        print("Wrong Input !!! \n", e)
        time.sleep(2)
        sys.exit()
    else:
        return x


y = int(input("please enter a number >> "))
i = err_handling(y)

print(i)

that it .

Mohammad
  • 7
  • 3
  • 1
    Why would `x = command` fail? – gosuto Dec 23 '18 at 11:35
  • if you use a string instead of integer it would be failed . am i wrong ? – Mohammad Dec 23 '18 at 11:40
  • `y = int(input("please enter a number >> "))` would already fail. – gosuto Dec 23 '18 at 11:42
  • you might want a `def get_integer():` function that does the input and the integerconversion until it works. – Patrick Artner Dec 23 '18 at 11:42
  • Possible duplicate of [Asking the user for input until they give a valid response](https://stackoverflow.com/questions/23294658/asking-the-user-for-input-until-they-give-a-valid-response) – Patrick Artner Dec 23 '18 at 11:43
  • i'm not trying to use try/except in the logic of my code but i'm trying to create a function that takes user input as an argument and does the try/except on it and returns the value if it didn't have any exception errors. – Mohammad Dec 23 '18 at 11:50

1 Answers1

-1

I think what you are trying to do is the following:

def err_handling(command=input("please enter a number: ")):
    try:
        command = int(command)
    except Exception:
        return 'wrong input!'
    else:
        return command

print(err_handling())
gosuto
  • 5,422
  • 6
  • 36
  • 57