Link Search Menu Expand Document

Exception Handling

Table of contents

  1. Description
  2. Errors without exception handling
  3. Errors with exception handling
  4. Instructional Video

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.

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()

Instructional Video