2

Let's imagine this code:

    try:
        if condition1 and condition2: # some_exception may happen here
            function1()
        elif condition3 and condition4: # some_exception may happen here
            function2()
        else:
            big
            block
            of
            instructions
    except some_exception:
        big
        block
        of
        instructions

As you can see I repeat big block of instructions (both are same). Is there a way to avoid repetition, but something different than putting the code in a function?

Some kind of different logic or using finally or else to try? I just can't figure it out.

Thanks in advance for helping me!

3
  • 2
    You could set a variable in your else and except clauses, and after the block, if the variable is set, call your big block of instructions. Commented Mar 14, 2019 at 19:19
  • 4
    Create a function from that big block and call it in the necessary places. Commented Mar 14, 2019 at 19:19
  • 2
    you could manually throw an exception in the else clause and only have to put the big block in the except Commented Mar 14, 2019 at 19:20

2 Answers 2

6

If you are averse to using a function, how about setting a variable in both places, and checking it later?

Something like this:

do_stuff = False
try:
    if condition1 and condition2: # some_exception may happen here
        function1()
    elif condition3 and condition4: # some_exception may happen here
        function2()
    else:
        do_stuff = True
except some_exception:
    do_stuff = True
    ...

if do_stuff:
    big
    block
    of
    instructions
Sign up to request clarification or add additional context in comments.

Comments

1
try:
    if condition1 and condition2: # some_exception may happen here
        function1()
    elif condition3 and condition4: # some_exception may happen here
        function2()
    else:
         raise some_exception('This is the exception you expect to handle')
except some_exception:
    big
    block
    of
    instructions

What about this ?

Changed to raise as suggested by kaelwood

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.