簡體   English   中英

嘗試除了不捕獲 FileNotFoundError

[英]Try except not catching FileNotFoundError

我正在嘗試捕獲 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

我做錯什么了?

從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