Search code examples
python-3.xexceptionpython-requeststry-catch

Python try/except flow if multiple except blocks are True


I would like to set "errored" to False if the exception is a Timeout error. I'm a little confused how try except flows work in python here (and surprisingly couldn't find any doc clarifying this - if anyone has one regarding how the blocks are executed please feel free to link), like if multiple exception blocks are true, do they all execute? Or just the first one? I assume the below doesn't work because we don't have access to 'r'

try:
    r = request(
        method="POST",
        ...
    )
    r.raise_for_status()
    resp = r.json()
    errored = False

except Exception as e:
    resp = _parse_json(e)
    errored = True
    if r.Timeout:
        errored = False

And the below is the effect I want, just not sure if it works as intended with the try/except flow

try:
    r = request(
        ...
    )
    r.raise_for_status()
    resp = r.json()
    errored = False

except Exception as e:
    resp = _parse_json(e)
    errored = True

except r.Timeout:
    errored = False

This is my first time handling/making post requests so please bear with me!


Solution

  • From what I've researched, in python the flow falls on the first except that matches the exception. In this case, place the timeout exception first.

    import socket
    import logging
    
    errored = False
    hostname = '10.255.255.1'
    port = 443
    socket.setdefaulttimeout(0.1)
    try:
        sock = socket.create_connection((hostname, port))
    
    except ZeroDivisionError:
        print('must not enter here')
    
    except socket.timeout as err:
        print('timeout')
        errored = False
    except Exception as ex:
        print('base exception')
        errored = True
    except:
        print('unknown exception')
        errored = True
    else:
        print('success')
    finally:
        print('This is always executed')  
    

    This code example makes a request that will timeout, will always fall into

    except socket.timeout as err:
    

    and then in finally. you can change the order of except to test.

    here a link about trycatch.

    Hope this helps