Exception Handling
Table of contents
Description
Exception handling allows programmers to deal with an error gracefully and avoid a sudden program crash. It is best practice to place error-prone code inside of try/except blocks.
- Python Docs Wiki: Handling Exceptions
Errors without exception handling
Run the program below, and enter non-numeric input at the prompt. Notice that the runtime error (exception) crashes the program.
Errors with exception handling
Run the program below, and enter non-numeric input at the prompt. Compare the output with the previous program.
Below is an example that uses a loop to re-prompt the user for correct input, instead of ending the program:
def main():
while True:
try:
quantity = int(input('How many cookies do you want? '))
break
except:
print('Please enter a whole number\n')
continue
print(f'\nExcellent! Here are your {quantity} cookies...')
if __name__ == '__main__':
main()