maxgemilian
maxgemilian

Reputation: 143

Combine except and else in Python

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

Upvotes: 2

Views: 558

Answers (2)

blhsing
blhsing

Reputation: 106588

You can assert that func1_flag is True in a try block before calling func1, and call func2 in the exception handler:

try:
    assert func1_flag
    func1()
except:
    func2()

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

Upvotes: 3

Sowasvonbot
Sowasvonbot

Reputation: 96

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.

Upvotes: 1

Related Questions