首页 > 解决方案 > 尝试除内尝试除

问题描述

下面的用法try...except正确吗?如果不是,我需要改变什么?

try:
    name_file = input('Welcome user, enter the name of the file to be opened: ')
    file = open('../' + name_file, 'r')
    # print(file.readlines(), end=' ')
except FileNotFoundError as err:
    print('File not found :(')
else:
    try:
        res = int(input('Which representation do you want to use? [1] Adjacency List - [2] Adjacency matrix'))
    except ValueError as err:
        print('Invalid option')

标签: pythonexception

解决方案


这是 try-except-else 的正确语法,如果用户为第二个提示输入非 int 值,将根据需要执行。但是,如果输入不同的数字,则不会抛出 ValueError。

  try:
    # Some Code
except:
    # Executed if error in the
    # try block
else:
    # execute if no exception
finally:
    # Some code .....(always executed)

https://www.geeksforgeeks.org/python-try-except/#:~:text=Else%20Clause%20In%20python%2C%20you%20can%20also%20use,the%20try%20clause%20does%20not% 20raise%20an%20异常。


推荐阅读