Is there any way to deal with exceptions within if statements, other than putting a try
, except
bracket around the whole lot, or to test for the exception on each line in advance?
For example, say i had the 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
was word_of_six_characters_or_more
this would work fine. If it is a shorter word it raises an exception on the line elif a[5] == "d"
. Obviously it is possible to test for exceptions in advance (e.g. changing elif a[5] == "d"
to elif len(a) >5 and a[5] =="d"
, which then relies on the first part being False
and thus the second never executed). My question is, is there any other way of just causing exceptions
to be treated as False
and to proceed to the next elif
statement rather than throwing up the exception - or similarly, to include try
except
clauses within a elif
line?
(obviously, it is possible that there is no way, and thus getting confirmation that adding in pre-tests for exceptions is how to proceed would be good to know).
(I should probably note, that my code is quite substantially more complicated than the above, and while i could put in pre-checks, there would be quite a lot of them, so just trying to see if there is a simpler solution.)