Search code examples
pythonwhile-looptry-except

try except in a while loop - python


Before explaining my question I share my code so it it easier to start directly from there.

import matplotlib.pylab as plt
import os

while True:
    try:
        img_name = input('Enter the image file name: ')
        img = plt.imread(os.path.join(work_dir, 'new_images_from_web\\', img_name + '.jpg'))
    except FileNotFoundError:
        print('Entered image name does not exist.')
        img_name = input('Please enter another image file name: ')
        img = plt.imread(os.path.join(work_dir, 'new_images_from_web\\', img_name + '.jpg'))

I would like the user to input the name of an image file, and whenever the file does not exist in the directory I want the user to input another file name instead of receiving an error message like the following:

FileNotFoundError: [Errno 2] No such file or directory:

In fact, with the code above, after the second mistaken input I receive an error message with exception FileNotFoundError, whereas I would like the loop to go on until an existing file name is given as input. What am I doing wrong in the while loop or in the rest of the code?


Solution

  • If a exception happens outside of try: except: it will crash your program. By asking a new input after the except: you are outside the capturing-"context": resulting in your program crashing.

    Fix :

    import matplotlib.pylab as plt
    import os
    
    while True:
        try:
            img_name = input('Enter the image file name: ')
            img = plt.imread(os.path.join(work_dir, 'new_images_from_web\\', img_name + '.jpg'))
            if img is None:
                print("Problem loading image")
            else:
                break  
        except FileNotFoundError:
            print('Entered image name does not exist.')
    
    # or check img here if you allow a None image to "break" from above
    if img:
        # do smth with img if not None
    

    It is important to also check/handle img being None because imread() can return a None if problems occure with loading the image (file exists / but corrupted... or a .txt)