1

Is it possible to make error handling functions so that I don't have to make error handling where the inputs are?

For example:

def error_handler(a,b,c):
    while True:
        try:
            a, b, c
        except ValueError:
            print("wrong")

def inputs():
   a = input("Write something")
   b = input("Write something")
   c = input("Write something")

How can I make that the function "inputs" understands that I have been doing a error_handling function without repeating the process?

Reblochon Masque
  • 35,405
  • 10
  • 55
  • 80
Reza amin
  • 37
  • 6

1 Answers1

0

You can create an input function that tests for the validity of the input.

In the following example, test for an int (but you can change that to the type you need.

def input_with_error_handler(txt):
    while True:
        try:
            raw_value = input(txt)
            return int(raw_value)
        except ValueError:
            print(f"{raw_value} must be an int")
    

a = input_with_error_handler("enter an int: ")
b = input_with_error_handler("enter an int: ")
c = input_with_error_handler("enter an int: ")
Reblochon Masque
  • 35,405
  • 10
  • 55
  • 80
  • just `return int(input(txt))` no need to `value`, why an `f` string for a literal string – rioV8 Nov 16 '20 at 14:27
  • rioV8 how do I then import it to the second function? – Reza amin Nov 16 '20 at 14:33
  • @rioV8 Can you please show with an example of what you mean because I think that my teacher said something like that – Reza amin Nov 16 '20 at 14:36
  • Sorry @rioV8, I posted incomplete code, thank you for pointing it out. `raw_value` collects the `input`; if an error is raised, it is used in the message (fstring) – Reblochon Masque Nov 16 '20 at 14:43
  • If a user enters something to the question `enter an int:` and the program responds with `Error: not an int entered` it does not apply to 3 fields back or some file content so no need to show what he has just entered – rioV8 Nov 16 '20 at 14:47