ajknzhol
ajknzhol

Reputation: 6450

How to continue loop after catching exception

The below code produces exception while handling non int values but it doesn't continue the loop but rather comes out from the loop raising error. My intention is to provide the value of 0 for exception cases.

Sample Input:

Common Ruby Errors 45min
Rails for Python Developers lightning

Code:

class TimeNotProvidedError(Exception):
    pass

def extract_input():
    lines = []
    __tracks = {}

    try:
        lines = [line.strip() for line in open('test.txt')]
    except FileNotFoundError as e:
        print("File Not Found", e)

    for line in lines:
        title, minutes = line.rsplit(maxsplit=1)
        minutes = int(minutes[:-3])
        try:
            __tracks[title] = minutes
        except TimeNotProvidedError:
            __tracks[title] = 0
    return __tracks

print(extract_input())

Traceback:

ValueError: invalid literal for int() with base 10: 'lightn'

Upvotes: 0

Views: 488

Answers (1)

Rob Kennedy
Rob Kennedy

Reputation: 163247

You're getting the error when converting to int with this line: minutes = int(minutes[:-3]). That line isn't in the try block, so the exception isn't caught. Move that line inside the try block, and you'll get the behavior you wanted.

Furthermore, the exception you're catching is TimeNotProvidedError, which isn't what int throws when a conversion fails. Instead, it throws ValueError, so that's the exception type you need to catch.


The mere act of assigning to __tracks[title] is unlikely to cause an exception, and if it does, re-trying with another assignment probably won't work anyway. What you probably want in your loop is this:

title, minutes = line.rsplit(maxsplit=1)
try:
    minutes = int(minutes[:-3])
except ValueError:
    minutes = 0
__tracks[title] = minutes

Upvotes: 3

Related Questions