This line 
rpc_client = rpcclient(agent, flags)
will throw an exception but since ensure gets called regardless of an exception having been thrown earlier in the code it still tries to disconnect.