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?
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.
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 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.
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With