Search code examples
pythonruntime-errorpython-imaging-library

How to continue the execution even if error happens


I have this code:

from PIL import Image

image1 = Image.open(r'1.jpeg')
im1 = image1.convert('RGB')
im1.save(r'1.pdf')

# Part 2
image1 = Image.open(r'2.jpeg')
im1 = image1.convert('RGB')
im1.save(r'2.pdf')

And I want to make sure that part 2 of the code will run even if the first file doesn't exist, how can I do that?


Solution

  • You could do that like so:

    from PIL import Image
    
    try:
        image1 = Image.open(r'1.jpeg')
        im1 = image1.convert('RGB')
        im1.save(r'1.pdf')
    except OSError:
        print("first file doesn’t exist!")
    
    image1 = Image.open(r'2.jpeg')
    im1 = image1.convert('RGB')
    im1.save(r'2.pdf')
    
    

    To read more about try-except read here: https://docs.python.org/3/tutorial/errors.html