0

I want to raise 2 errors within a Try-block and catch them both simultaneously with one Except-block, but handle them differently.

The reason is, that I want to avoid a situation where xy errors are raised inside a Try-block, but just one of them is noticed and handled accordingly.

This is my attempt:

try:
    x = 1 / 0 # This will raise a ZeroDivisionError
    y = int('foo') # This will raise a ValueError
except (ZeroDivisionError, ValueError) as e: 
    if isinstance(e, ZeroDivisionError): # Should handle the ZeroDivisionError
        print("Error: Cannot divide by zero!")
    if isinstance(e, ValueError):        # Should handle the ValueError
        print("Error: Invalid value provided!")

Current Output: Error: Cannot divide by zero!

The Output SHOULD be:

Error: Cannot divide by zero!
Error: Invalid value provided!

I know that I can use multiple Except-blocks to handle different Exceptions (but only one at a time).
I know that I also can use two Try-blocks to get a workaround like this:

try:
    x = 1 / 0  # This will raise a ZeroDivisionError
except ZeroDivisionError:
    print("Error: Cannot divide by zero!")

try:
    y = int('foo')  # This will raise a ValueError
except ValueError:
    print("Error: Invalid value provided!")

But this is not what I want to do.

I'm using Python 3.9.6

Is my requirement even possible? It has to be, because otherwise handling several Exceptions in a tuple would only be useful to avoid redundant Except-blocks if the execution code is meant to be the same.

Nico
  • 3
  • 1
  • It is not possible, imagine changing your two lines to `x = int("foo")` and then `y = x / 0` does it even make sense for Python to continue executing that code block considering one of the lines had an exception? How would the sequencing of the code even work? Does the sequence with two try-except not make much more sense? – Abdul Aziz Barkat Mar 22 '23 at 16:33
  • @Tomerikoo this question is different from that one, OP wants execution to continue and there to be only one try block. – Abdul Aziz Barkat Mar 22 '23 at 16:36
  • @AbdulAzizBarkat Yeah I just figured that out. The whole point of `try/except` is to stop execution of the `try` block and execute the `except`. You can't "go back" to execute the `try` block... – Tomerikoo Mar 22 '23 at 16:38

0 Answers0