Search code examples
pythontry-catchbreak

Jump from try to except using python


I searching the way to break the try and go into the except (This example has an syntaxerror in the break line)

def fool():
    return 0

try:
    var = fool()
    if var == 0:
        pass  # from here jump to except 
except:
    fool2()

Another way i thought is:

var = fool()
if var == 0:
     fool2()

Another solution more pythonic ?


Solution

  • You can raise a generic Exception:

    try:
        var = fool()
        if var == 0:
            raise Exception
    except:
        fool2()
    

    But this is not good programming: you should always be clear on which exceptions you're going to catch.

    The Zen of Python states that "Errors should never pass silently".

    So, this could be a better implementation:

    class FoolException(Exception):
        pass
    
    def fool():
        if everything_ok:       
            return 0
        raise FoolException()
    
    
    try:
        var = fool()
        if var == 0:
            raise FoolException() 
    except FoolException:
        fool2()
    

    This will prevent you to catch unwanted exceptions (e.g. IndexError, ZeroDivisionError...)

    BUT, I think the best pattern here is to call fool2 separately:

    def fool():
        return 0
    
    
    try:
        var = fool()
        if var == 0: #Here I manage controlled events
            fool2()
    except: #Here I manage uncontrolled events
        fool2()
    

    This way is even better, because it isolates the instruction which can raise exceptions:

    def fool():
        return 0
    
    
    try:
        var = fool()
    except: #Here I manage uncontrolled events
        fool2()
    else:  #Here I manage controlled events
        if var == 0:
            fool2()