Search code examples
pythontry-catch

Try except not catching FileNotFoundError


I'm trying to catch the FileNotFoundError and break the code when it occurs, but for some reason it's not working, im still getting the error and the code is not breaking, here is my code

file_name = input("Choose a file: ")
def split_columns(file_name):
    x_values = []
    y_values = []     
    try:                                            
        with open(file_name) as f:
            for line in f:
                row_values = line.split()
                print(row_values)
                x_values.append(float(row_values[0]))
                y_values.append(float(row_values[1]))
    except FileNotFoundError:
        print('This file does not exist, try again!')
        raise
    return x_values, y_values

What did i do wrong?


Solution

  • Take the try/except out of the function, and put it in the loop that calls the function.

    def split_columns(file_name):
        x_values = []
        y_values = []     
        with open(file_name) as f:
            for line in f:
                row_values = line.split()
                print(row_values)
                x_values.append(float(row_values[0]))
                y_values.append(float(row_values[1]))
        return x_values, y_values
    
    while True:
        file_name = input("Choose a file: ")
        try:
            x_values, y_values = split_columns(file_name)
            break
        except FileNotFoundError:
            print('This file does not exist, try again!')