Looking for an alternative for nested try-except block in python

Question:

I was making an image resizing program using the pillow module in python.

I like to program a perfect error-catching program, so I used many nested try-catch blocks in the program below. It works perfectly but I need to modify the code in less number of sloc and try-except blocks.

Please suggest to me a way not to use many try-except blocks but the program works without a problem (with perfect error catching).

def GettingValues():
    try:
        img = im.open(input('Enter image name or path: ')) # give image path if image not in current folder
        try:
            width = int(input('Enter required width: '))
            height = int(input('Enter required height: '))
            try:    
                Resizer(img, width, height)
            except:
                print('Error calling Resizer function. Try Again')            
        except:
            print("Error in Width or Height Values. Try Again")    
    except:
        print("Error in file name. Try Again") 
Asked By: Ajay

||

Answers:

Just use a single try and different except clauses (including one for unexpected errors):

def GettingValues():
    try:
        img = im.open(input('Enter image name or path: ')) # give image path if image not in current folder
        width = int(input('Enter required width: '))
        height = int(input('Enter required height: '))
        Resizer(img, width, height)
    except ResizerError: print('Error calling Resizer function. Try Again')            
    except ValueError: print("Error in Width or Height Values. Try Again")    
    except OSError: print("Error in file name. Try Again") 
    except Exception: print("Unknown error. Try Again")

Note: I’m assuming you defined a ResizerError and Resizer raises it if something goes wrong

Answered By: gimix