close

how to continue for loop after exception?

Hello Guys, How are you all? Hope You all Are Fine. Today We Are Going To learn about how to continue for loop after exception in Python. So Here I am Explain to you all the possible Methods here.

Without wasting your time, Let’s start This Article.

Table of Contents

how to continue for loop after exception?

  1. how to continue for loop after exception?

    Ok, got it working, i needed to add the Continue, mentioned by Mark and also the previous if check inside finally was always returning true so that was fixed aswell.

  2. continue for loop after exception

    Ok, got it working, i needed to add the Continue, mentioned by Mark and also the previous if check inside finally was always returning true so that was fixed aswell.

Method 1

Your own answer is still wrong on quite a few points…

import logging
logger = logging.getLogger(__name__)

def do_connect(self):
    """Connect to all hosts in the hosts list"""
    for host in self.hosts:
        # this one has to go outside the try/except block
        # else `client` might not be defined.
        client = paramiko.SSHClient()
        try:
            client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
            client.connect(host['ip'], port=int(host['port']), username=host['user'], timeout=2)

        # you only want to catch specific exceptions here
        except paramiko.SSHException as e:
            # this will log the full error message and traceback
            logger.exception("failed to connect to %(ip)s:%(port)s (user %(user)s)", host) 

            continue
        # here you want a `else` clause not a `finally`
        # (`finally` is _always_ executed)
        else:
            self.connections.append(client)

Method 2

Ok, got it working, i needed to add the Continue, mentioned by Mark and also the previous if check inside finally was always returning true so that was fixed aswell.

Here is the fixed code, that doesnt add failed connections and continues the loop normally after that:

def do_connect(self):
    """Connect to all hosts in the hosts list"""
    for host in self.hosts:
        try:
            client = paramiko.SSHClient()
            client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
            client.connect(host['ip'], port=int(host['port']), username=host['user'], timeout=2)
        except:
            continue
            #client.connect(host['ip'], port=int(host['port']), username=host['user'], password=host['passwd'])

        finally:
            if client._agent is None:
                pass
            else:
                self.connections.append(client)

Summery

It’s all About this issue. Hope all Methods helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which Method worked for you? Thank You.

Also, Read