2

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!

1
  • 6
    No it can't. They run foo2() under different conditions. Commented Apr 19, 2011 at 8:26

2 Answers 2

1

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...

Sign up to request clarification or add additional context in comments.

5 Comments

This does not have the same behavior as the first example.
@neurino: This works like or, is not it? He asks for and.
@Fenikso: got it, you are right. Then I hope the OP explains under which precise conditions wants dosth executed...
Thx all! After I checked the python doc, I realized the except can hold a tuple multi conditions. This works like a or condition.
@demoslam - yes, but it won't behave the same way you wrote in your first example.
1

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()

1 Comment

Can be simplified via zip() and for/else.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.