Home > Software design >  Handling same type of exceptions in multiple ways
Handling same type of exceptions in multiple ways

Time:03-02

I have one method that give same type of exception but I need to handle it in different ways like:

try:
    # lets authenticate
except AuthenticationException:
       #handle it in way 1
except AuthenticationException:
      # handle it in way 2
except AuthenticationException:
      # handle it in way 3
except AuthenticationException:
      # handle it in way 4

We get same error AuthenticationException but it should not fail; it should try all 4 possible ways.

Is there any good way I can achieve this?

CodePudding user response:

As @FrancisCagney has already explained, you would expect each except to cater for unique conditions. The obvious solution would be to try to write the exception processing in such a way that it would handle the possible problems so that you only execute the relevant handler, rather than trying them sequentially. However, if you want it to try 4 different things, each of which might cause a new exception, one way of catering for this would be to wrap those 4 different ways in their own try/except statements:

try:
    # lets authenticate
except AuthenticationException:
    try:
       # handle it in way 1
    except:
        pass
    try:
       # handle it in way 2
    except:
        pass
    try:
       # handle it in way 3
    except:
        pass
    try:
       # handle it in way 4
    except:
        pass

CodePudding user response:

The point of multiple except clauses is to handle different exceptions differently.

try:
    <things that might fail>
except NameError as ex:
    <handle name error>

except AuthenticationException as ex:
    if ex.cause == 0:
        <handle cause 0>
    elif ex.cause == 'hello':
        <handle cause 1>

Now your AuthenticationException might have more information indicating why the exception was raised, but that's handled with if inside the single except clause for this exception.

  • Related