0

I have a function that in some cases might get as input something that is not suited for what the function is supposed to do. When this is the case, rather than stopping the program and returning an error, I would like the function to simply return something specific, like for example the string there is something wrong in the input.

Let me show a specific example. This is a function that takes as input the string indicating a chess move and returns the actual move in the form of a list (initial square and final square).

def move_name_converter(name):
    columns=list(string.ascii_lowercase)[:8]
    columns.reverse()
    move=[]
    move.append([int(name[1])-1,columns.index(name[0])])
    move.append([int(name[3])-1,columns.index(name[2])])
    if len(name)==5:
        move.append(name[4])
    return move

if I give a proper input everything works fine:

print move_name_converter('a2a3')

will correctly return

[[1, 7], [2, 7]]

If instead I give a bad input:

print move_name_converter('whatever')

it returns a ValueError. Rather than returning an error (any kind of error), I would like the function to just print a string like this is not a valid input. I could solve the issue by carefully consider every possible way the input could be bad, but is there a way to generically make the function return a given output whenever there is an error?

3sm1r
  • 520
  • 4
  • 19
  • 1
    You could wrap the entire body of the function in a `try: ... except Exception: return "there is something wrong"`. – mkrieger1 Jun 22 '20 at 19:27
  • Printing a string as an error sort of defeats the purpose of errors which is that the caller can handle it programmatically. Raising a `ValueError` or `TypeError` already seems like the appropriate response for an invalid input parameter. Maybe returning a flag like `None` is appropriate for some functions, but returning a string description basically never is since this functionality is supported by errors. – ggorlen Jun 22 '20 at 19:28
  • May I ask who and where inserts the parameters for the function? – JSRB Jun 22 '20 at 19:28
  • That being said, exceptions are specifically made for separating error information from return values. – mkrieger1 Jun 22 '20 at 19:29
  • And *printing* an error message is even worse than returning it, because it cannot be handled by the caller at all. – mkrieger1 Jun 22 '20 at 19:30
  • @Jonas it is supposed to be an external input, but whoever types it can make human mistakes. when it happens, I don't want the system to crash completely. – 3sm1r Jun 22 '20 at 19:36
  • 1
    @3sm1r then u either go with the posted answer or you add parameters as inputs to your function and create controls for each to ensure the inputted params are in the required format. Otherwise return raise error – JSRB Jun 22 '20 at 19:37
  • @mkrieger1 if I use a `while` loop, then I can make it re-ask for the input until it is suited for the function. This is what the idea is: "if the input is ok, do your job, otherwise ask for another input" – 3sm1r Jun 22 '20 at 19:39
  • 1
    Then this is a duplicate of https://stackoverflow.com/questions/23294658/asking-the-user-for-input-until-they-give-a-valid-response – mkrieger1 Jun 22 '20 at 19:40

1 Answers1

2

You can use a try except statement to catch the ValueError and return a custom string if it occurs:

def move_name_converter(name):
    try:
        columns=list(string.ascii_lowercase)[:8]
        columns.reverse()
        move=[]
        move.append([int(name[1])-1,columns.index(name[0])])
        move.append([int(name[3])-1,columns.index(name[2])])
        if len(name)==5:
            move.append(name[4])
        return move
    except ValueError:
        return 'This is not a valid input'

print (move_name_converter('a2a3'))
[[1, 7], [2, 7]]
print (move_name_converter('whatever'))   
This is not a valid input
Koralp Catalsakal
  • 1,114
  • 8
  • 11
  • TY. Is it possible to include other kinds of errors other than `ValueError`, like for example `IndexError` ? – 3sm1r Jun 22 '20 at 19:46
  • 1
    Yes, you can add more except statements such as `except IndexError` to catch different errors – Koralp Catalsakal Jun 22 '20 at 19:49
  • Nice. I have noticed that if I use `Exception` it includes both `ValueError` and `IndexError` at the same time. I'm saying this because I am not sure about all kinds of error that can emerge from a typo in this case. – 3sm1r Jun 22 '20 at 19:59