Python try-except with of if else
python, refactoring, try-catch
Solution
You could try the following:
class PKIsFalseException(Exception):
pass
try:
pk = a_method_that_may_raise_an_exception()
if not pk: raise PKIsFalseException()
except (PKIsFalseException, CatchableExceptions):
method_to_be_executed_in_case_of_exception_or_pk_is_false()
I have updated with specific exception catching instead of catching all exceptions, which is always bad practice as others have pointed out. Assuming that your method will throw one of `CatchableExceptions`.
Problem
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?