user2824889
user2824889

Reputation: 1185

Conditional except statements in Python

Is there a way to make an except statement conditional - in other words, only catch a type of exception if the condition is true? This is the idea I have, but it seems like it won't work

try:
  <code>
if condition == True:
  except Exception as e:
    <error handling>

Upvotes: 5

Views: 11284

Answers (3)

L Selter
L Selter

Reputation: 352

You could use different exceptions for each case and catch them seperately:

import random


class myException_1(Exception):

    pass

class myException_2(Exception):
    pass


try:
    a = random.randint(0,10)
    if a % 2 == 0:
        raise myException_1("something happened")
    elif a % 3 ==0:
        raise myException_2("something else happened")
    else:
        print("we made it!")
except myException_2 as e:
    print("a was divisible by 3")
    print(e)
except myException_1 as e:
    print("a was divisible by 2")
    print(e)

Upvotes: 0

Daniel Roseman
Daniel Roseman

Reputation: 599530

No, you can't do that. What you can do is catch the error then check the condition inside the except block and re-raise if necessary:

except Exception as e:
    if not condition:
        raise

Upvotes: 9

FHTMitchell
FHTMitchell

Reputation: 12157

Not like that, but I find this to be the cleanest solution

try:
  <code>
except Exception as e:
    if condition:
        <error handling>
    else:
        raise  # re raises the exception

Upvotes: 3

Related Questions