Reputation: 553
everyone, my python code is something like this:
try:
foo1()
except FooError1:
try:
foo2()
except FooError2:
dosth()
raise raisesth()
I wonder if there is a try-except support for multi conditions or compound conditions in python, thus my code could be simplified as:
try:
foo1()
foo2()
except FooError1 and FooError2:
dosth()
raise raisesth()
Thanks!
Upvotes: 2
Views: 2856
Reputation: 9451
Exception and ;-).
def foo1():
return 1/0
def foo2():
return s
def do_something():
print("Yes!")
def exception_and(functions, exceptions, do_something):
try:
functions[0]()
except exceptions[0]:
if len(functions) == 1:
do_something()
else:
exception_and(functions[1:], exceptions[1:], do_something)
# ================================================================
exception_and([foo1, foo2], [ZeroDivisionError, NameError], do_something)
# Behaves the same as:
try:
foo1()
except ZeroDivisionError:
try:
foo2()
except NameError:
do_something()
Upvotes: 1
Reputation: 12395
I suggest you to read python documentation.
I assume you want dosth
called if foo1()
or foo2()
raise an exception you want to handle in dosth()
, like in your second code block.
try:
foo1()
foo2()
except (FooError1, FooError2):
dosth()
raise raisesth()
As you may ask a and
condition in your except
statement I remember you an exception must be handled as soon as it raises or execution will stop so you can't tell the interpreter to go ahead waiting for FooError2
to come...
Upvotes: 1