If the inputs from the user are valid it does not throw any errors. I have not quite ironed out all the errors caused by bad inputs.This is one important aspect of failing gracefully - coping with user error. Clearly the program isn't good if it fails and throws a syntax error when the user enters valid inputs. But a good program should cope with invalid inputs as well. In terms of the latest program I have created, most of the inputs are tested to see that they valid - there is a function in the program that is dedicated to making sure that inputs that are expected to be integers are indeed integers:
def checkint(num):
try:
int(num)
check = True
except:
print("Not a valid number!")
check = False
return check
Simple but it does its job. Note that it uses a try...except... structure, which is a very useful thing when checking for something that might cause syntax errors. If a syntax error would occur in a try...except... structure, it is caught before the program crashes, and the except part takes over.
Another aspect and set of errors is when the program needs to connect to an external resource, such as a file. This can happen when either opening a text file or when using the SQLite module to connect to a database file, or maybe trying to connect to a website. If the file doesn't exist, or maybe not in the folder the program is using as the path, then generally the program will throw an error and end. Are there alternatives? Could the programmer anticipate this? If the external file is essential for the running of the program then the best case scenario may be that the Python program closes, leaving an error message saying that it could not find the relevant file. Should the user be prompted to enter an alternative file path? Could the program run with a different file? Should this alternative file's name be included in the code or should the user be prompted to input it? As above, a try...except... structure can catch these problems before they cause the program to crash.
Asking the programmer to anticipate all of these problems could add substantially to the code, but not anticipating them at all is courting even more problems, especially when untrained users are let loose on the program. I admit that I do make assumptions about things working as expected (including user inputs) when creating the programs you have already seen on this blog. For example, the historical figures database assumes that SQLite is already installed, and that the history1.db with its three tables and their respective columns is already set up, ready to at least receive new data. That's simply how things are on my computer. Running the program on a different computer will cause problems because the program does not anticipate these differences between computers.
No comments:
Post a Comment