简体   繁体   English

尝试除了不捕获 FileNotFoundError

[英]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我正在尝试捕获 FileNotFoundError 并在它发生时破坏代码,但由于某种原因它不起作用,我仍然收到错误并且代码没有破坏,这是我的代码

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?我做错什么了?

Take the try/except out of the function, and put it in the loop that calls the function.从function中取出try/except ,放到调用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!')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM