Handling exceptions within if statements in Python -
is there way deal exceptions within if statements, other putting try
, except
bracket around whole lot, or test exception on each line in advance?
for example, had simplified code:
if a[0] == "a": return("foo") elif a[1] == "b": return("bar") elif a[5] == "d": return("bar2") elif a[2] == "c": return("bar3") else: return("baz")
if a
word_of_six_characters_or_more
work fine. if shorter word raises exception on line elif a[5] == "d"
. possible test exceptions in advance (e.g. changing elif a[5] == "d"
elif len(a) >5 , a[5] =="d"
, relies on first part being false
, second never executed). question is, there other way of causing exceptions
treated false
, proceed next elif
statement rather throwing exception - or similarly, include try
except
clauses within elif
line?
(obviously, possible there no way, , getting confirmation adding in pre-tests exceptions how proceed know).
(i should note, code quite substantially more complicated above, , while put in pre-checks, there quite lot of them, trying see if there simpler solution.)
well, there 2 ways handle this. slice single character empty if doesn't exist. e.g.,
if a[0:1] == "a": return("foo") elif a[1:2] == "b": return("bar") elif a[5:6] == "d": return("bar2") elif a[2:3] == "c": return("bar3") else: return("baz")
or, write wrapper function ignore indexerror
s. e.g.,
def get(obj, index): try: return obj[index] except indexerror: return if get(a, 0) == "a": return("foo") elif get(a, 1) == "b": return("bar") elif get(a, 5) == "d": return("bar2") elif get(a, 2) == "c": return("bar3") else: return("baz")
Comments
Post a Comment