0

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?

Code Carbonate
  • 640
  • 10
  • 18
  • 2
    Show us some code, please. Sounds like you're looking for `try: except ...:` with different `...`s; see https://docs.python.org/3/tutorial/errors.html#handling-exceptions – AKX Oct 29 '20 at 11:52
  • Does this answer your question? [Python: One Try Multiple Except](https://stackoverflow.com/questions/6095717/python-one-try-multiple-except) – Gino Mempin Oct 29 '20 at 12:22
  • Try `tkinter.messagebox.showerror` after catching it with `try` and `except`? – Delrius Euphoria Oct 29 '20 at 12:56

1 Answers1

6

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'
JPI93
  • 1,507
  • 5
  • 10