Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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!')
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading