python - 尝试除内尝试除
问题描述
下面的用法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')
解决方案
这是 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)
推荐阅读
- android - 在哪里添加工具栏和导航栏
- c++ - 编译BST源代码时得到LNK2019和LNK1120
- jquery - 动态元素上的 Jquery 点击事件不适用于变量
- python - 验证字典列表中元素的正确格式的最佳实践
- wpf - 将 System.Windows.Media.Brush 作为图像文件保存到磁盘
- javascript - 无法从正文 onload 调用函数(未捕获的引用错误:未定义 resetLoginForm)javascript
- outlook - 我可以使用 Outlook 加载项将表格添加到邮件正文中吗
- angular - 更新后 Angular 6/7 服务工作者无法加载延迟加载的模块,意外令牌 <
- powershell - 过滤组成员资格以从一个用户复制到另一个用户
- javascript - 切换标签后 setInterval() 行为怪异