0

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'
2
  • can you add a couple of lines from test.txt Commented Feb 13, 2015 at 16:49
  • stackoverflow.com/questions/2083987/… - you might try using 'continue' Commented Feb 13, 2015 at 16:51

1 Answer 1

3

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.