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.