2

By specific exception I mean differentiating between the same exception but different errors from the same exception rather than differentiating between different exceptions completely, for example:

With the ZeroDivisionError exception, there are multiple errors. One of which being:

>> 0/0
>> ZeroDivisionError: division by zero

And another being:

>> 0**-1
>> ZeroDivisionError: 0.0 cannot be raised to a negative power

Same exception, different errors.

I want to only except one type of error which is the 0 to a negative power error and pass it, but with any other ZeroDivisionError I want to re-raise the error but with an empty message.

The first thing I tried was:

try:... # Some code
except ZeroDivisionError as e:
    if e!="0.0 cannot be raised to a negative power":
        raise ZeroDivisionError("")

But that wouldn't work, no other errors being raised, just simply wouldn't work.

So I started investigating and found out that e is not a string type but instead a ZeroDivisionError type.

So if you do this:

try:print(0/0)
except ZeroDivisionError as e:
    print(type(e))

The output would be: <class 'ZeroDivisionError'>

So in my second attempt I did the same thing as before but instead compared e to a certain ZeroDivisionError type error:

try:... # Some code
except ZeroDivisionError as e:
    if e!=ZeroDivisionError("0.0 cannot be raised to a negative power"):
        raise ZeroDivisionError("")

But again, same way as before, didn't work.

So one last thing came to me which was including the error string when excepting the exception:

try:... # Some code
except ZeroDivisionError("0.0 cannot be raised to a negative power"):
    raise ZeroDivisionError("")

But anticipating failure, it failed.

So.. is it possible? Or can you only except certain exceptions no matter what error within the exception?

yungmaz13
  • 139
  • 11

0 Answers0