Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python try-except with of if else

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?

like image 438
Varghese Chacko Avatar asked Dec 18 '13 07:12

Varghese Chacko


People also ask

Can I use try-except instead of if-else?

Most of the people don't know that Try-Except block can replace if-else (conditional Statements). Yes, You read it right! It can be done. We can use Try ( Exception Handling ) instead of using normal conditional statements.

Can I use try without except in Python?

Use the pass statement to use a try block without except. The pass statement does nothing and is used when a statement is required syntactically but the program requires no action.

What is if-else block in exception?

What are 'if' and 'else'? if: It checks if any condition is “true” or not, if it is true then it executes the code inside the if block. else: If the condition is “false” which is checked by the if block, then else block executes the other code within it.


1 Answers

What about something like:

try:
    pk = a_method_that_may_rise_an_exception()
except HandleableErrors:
    pk = False
finally:
    if pk:
        process_pk()
    else:
        method_to_be_executed_in_case_of_exception_or_pk_is_false()

Really, we don't even need the finally clause here...

try:
    pk = a_method_that_may_rise_an_exception()
except HandleableErrors:
    pk = False

if pk:
    process_pk()
else:
    method_to_be_executed_in_case_of_exception_or_pk_is_false()
like image 54
mgilson Avatar answered Sep 29 '22 11:09

mgilson