Home > Back-end >  Combine except and else in Python
Combine except and else in Python

Time:09-18

Consider you have two functions func1 and func2, where func2 is the fallback option for func1. However, you can also choose by a flag to always go for func2. Is there a way to avoid redundant code and unite except/else since they have the same content?

if func1_flag == true:
    try:
        func1()
    except:
        func2()
else:
    func2()

CodePudding user response:

You can include the if statement in the try block and raise an exception if func1_flag isn't True:

try:
    if not func1_flag:
        raise ValueError
    func1()
except:
    func2()

Note that you should specify the exact exception types in the except statement if you know which ones func1 produces.

CodePudding user response:

There is a way, but it's kind of ugly.

try:
    if not func1_flag:
        raise Exception
    func1()
except:
    func2()

This will raise an exception if the func1_flag is false. Then the except block is executed. You could raise an exception in func1() either.

But I don't see a big problem in your style.

  • Related