Python try-except with of if else

Viewed 70343

I have the following code:

    try:
        pk = a_method_that_may_raise_an_exception()
    except:
        method_to_be_executed_in_case_of_exception_or_pk_is_false()
    else:
        if pk:
            process_pk()
        else:
            method_to_be_executed_in_case_of_exception_or_pk_is_false()

This could be written as:

    try:
        if a_method_that_may_raise_an_exception():
            process_pk()
        else:
            method_to_be_executed_in_case_of_exception_or_pk_is_false()
    except:
        method_to_be_executed_in_case_of_exception_or_pk_is_false()

I am not happy that the method method_to_be_executed_in_case_of_exception_or_pk_is_false() appears twice, i.e in else of both if and try...except.

Is there a better way to do this?

3 Answers
Related