同时获得ValueError和超出范围?

时间:2017-06-12 04:09:11

标签: python

def open_file():
'''Repeatedly prompt until a valid file name allows the file to be opened.'''
    while True:
        year_str = input("Enter a year where 1990 <= year <= 2015: ")
        file_name = ("year" + year_str + ".txt")
        if int(year_str) <= 2015 and int(year_str) >= 1990:
            try:
                fp = open(file_name,'r')
                return fp
            except FileNotFoundError:
                print("Error in file name: " + file_name + ". Please try again.")
                open_file()
        else:
            print("Error in year. Please try again.")
            open_file()   

以上是我的代码。我应该在范围内打开一个文件(1990,2016)。我要经历的考验是当我输入&#39; xxxx&#39;或者超出范围的年份,它将打印

Error in year. Please try again

然而,当我运行我的代码时,python显示了

ValueError: invalid literal for int() with base 10: 'xxxx'

我认为else语句可以同时处理值错误并超出范围。我该如何解决这个问题?

3 个答案:

答案 0 :(得分:1)

我认为此处的其他答案错过了一些重要的内容 - 您在int(year_str)语句中收到错误,但此处的所有人都建议您在打开文件时添加try...except块。这对你没有帮助。

你需要的是:

def open_file():
'''Repeatedly prompt until a valid file name allows the file to be opened.'''
    while True:
        year_str = input("Enter a year where 1990 <= year <= 2015: ")
        file_name = ("year" + year_str + ".txt")
        try:
            year_int = int(year_str)
        except ValueError:
            print("Error in year. Please try again.")
            continue # to try again within your loop
        if year_int <= 2015 and year_int >= 1990:
            try:
                fp = open(file_name,'r')
                return fp
            except FileNotFoundError:
                print("Error in file name: " + file_name + ". Please try again.")
        else:
            print("Error in year. Please try again.")

open_file()   

答案 1 :(得分:0)

您的代码应该是这样的:

def open_file():
    """ Repeatedly prompt until a valid file name allows the file to be opened."""
    while True:
        year_str = input("Enter a year where 1990 <= year <= 2015: ")
        file_name = ("year" + year_str + ".txt")
        if int(year_str) <= 2015 and int(year_str) >= 1990:
            try:
                fp = open(file_name, 'r')
                return fp
            except IOError:
                print("Error in file name: " + file_name + ". Please try again.")
                open_file()
        else:
            print("Error in year. Please try again.")

open_file()

请注意,python中的docstring应使用三重双引号编写。

python2中没有FileNotFoundError异常它存在于python3中。当您需要在python2中捕获文件未找到的异常时,可以使用IOError。

答案 2 :(得分:0)

如果您希望通过通用句柄块处理FileNotFoundError以外的所有类型的例外,那么您可以将else语句更改为通用except

def open_file():
'''Repeatedly prompt until a valid file name allows the file to be opened.'''
    while True:
        year_str = input("Enter a year where 1990 <= year <= 2015: ")
        file_name = ("year" + year_str + ".txt")
        if int(year_str) <= 2015 and int(year_str) >= 1990:
            try:
                fp = open(file_name,'r')
                return fp
            except FileNotFoundError:
                print("Error in file name: " + file_name + ". Please try again.")
                open_file()
            except Exception:
                print("Error in year. Please try again.")

open_file()

编辑1: 如果您希望从异常中获取错误消息,可以在捕获时给它命名:

except Exception as e:
    print('Error occured: %s' % e)