How to handle multiple exceptions in Python 3? [closed]

I am creating a Calculator application using Tkinter. I require multiple types of exception statements to intimate the user by different types of outputs for different exceptions caused by him.

For example:

If the user divides a number by zero, then division by zero error arises. In this case I must create an exception statement that handles only division by zero error.

At the same time, if the user enters an invalid operation like ‘100++2’ instead of ‘100+2’ then an invalid syntax error arises. In this case I must specify a different exception statement in the same try to handle this condition differently.

So, how to do this?

Answer

It may be worth checking out the Errors and Exceptions docs.

In short, you can specify behaviour for different Exception types using the except ExceptionType: syntax where ExceptionType is an Exception derived from the Python Exception class – a list of built-in Python exceptions can be found here.

It is important to note that when an Exception is raised in a try block, Python will execute the code within the first Except block that matches the Exception raised in a top-down manner. For this reason, except Exception: is usually found at the bottom in a given try/except chain as to provide default behaviour for unspecified exceptions that may be raised, it is not first as any Exception raised will trigger this behaviour and thus would make other Except statements within the chain moot.

Example

The below example illustrates the above points.

Here eval() has been used for demonstrative purposes only, please be aware of the inherent dangers of using eval() before you consider using it in your own code.

def demo(e):
    try:
        eval(e)
    except ZeroDivisionError as e:
        print("ZeroDivisionError caught")
        print(e)
    except IndexError as e:
        print("IndexError caught")
        print(e)
    except Exception as e:
        print("Other Exception caught")
        print(e)
    
examples = ["10/0", "[0,1,2][5]", "int('foo')"]

for e in examples:
    demo(e)
    print()

Output

ZeroDivisionError caught
division by zero

IndexError caught
list index out of range

Other Exception caught
invalid literal for int() with base 10: 'foo'