Search code examples
pythontry-catch

Python: raise inside of try block, for breaking out of it


I have a function that needs to execute one of two blocks of code:

  • code A
  • code B

it needs to execute code B if some variable check is False, or if code A fails. Either code A or B must be executed, not both. The way I wrote this is:

try:
    if check:
        raise TypedError('')
    # code A
except TypedError:
    # code B

I feel bad for this for two reasons:

  • TypedError is the class of errors I expect from code A, but it has nothing to do with my code, in fact, is specific of some package I'm using.
  • If check is True and an error occurs in code B, it appears from traceback that it occurred while handling another error, which is untrue and potentially confusing.

Do you think there is a more pythonic way of writing this same program?


Solution

  • the nice and useful comment from @FrankYellin made me realise there is a better solution I couldn't think about before:

    if check:
        try:
            # code A
        except TypedError:
            check = False
    if not check:
        # code B
    

    I think this is better, and only one line longer. Thank you for bearing my silly question.