python-3.x - 如何在一个“尝试”块中引发同一错误的多个异常
问题描述
我正在创建一个程序,可让您从 Python 启动应用程序。我已经设计了它,所以如果某个网络浏览器没有下载,它会默认为另一个。不幸的是,try 块似乎只对一个“除了 FileNotFoundError”起作用。有没有办法在同一个 try 块中有多个这些?下面是我的(失败的)代码:
app = input("\nWelcome to AppLauncher. You can launch your web browser by typing '1', your File Explorer by typing '2', or quit the program by typing '3': ")
if app == "1":
try:
os.startfile('chrome.exe')
except FileNotFoundError:
os.startfile('firefox.exe')
except FileNotFoundError:
os.startfile('msedge.exe')
如果用户没有下载 Google Chrome,程序会尝试启动 Mozilla Firefox。如果找不到该应用程序,它应该打开 Microsoft Edge;相反,它会在 IDLE 中引发此错误(请注意,我故意拼错了 chrome.exe 和 firefox.exe,以模拟本质上不存在的程序):
Traceback (most recent call last):
File "C:/Users/NoName/AppData/Local/Programs/Python/Python38-32/applaunchermodule.py", line 7, in <module>
os.startfile('chome.exe')
FileNotFoundError: [WinError 2] The system cannot find the file specified: 'chome.exe'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:/Users/NoName/AppData/Local/Programs/Python/Python38-32/applaunchermodule.py", line 9, in <module>
os.startfile('frefox.exe')
FileNotFoundError: [WinError 2] The system cannot find the file specified: 'frefox.exe'
有没有办法在一个 try 块中引发两个相同的异常?
解决方案
for exe in ['chrome.exe','firefox.exe','msedge.exe']:
try:
os.startfile(exe)
break
except FileNotFoundError:
print(exe,"error")
推荐阅读
- java - 有没有办法用java递归检查一个字符串是否包含至少一个大写字母?
- gradle - 如何在 Gradle 中排除传递运行时依赖项
- python - pip install grpcio 无法构建,但在 2 周前工作
- typescript - TypeScript 高级类型 - 泛型函数内部出现无法访问错误的问题
- java - 从 Head First Java 开始
- ios - 直接在 Outlook for iOS 中打开指向特定电子邮件的链接(URI 方案/深层链接)
- php - ArrayObject 在 PHP 7.4 中不能与 end() 一起使用
- synchronization - 在 Vulkan 的 Acquire-Present 场景中“同步”渲染通道布局转换与信号量
- testlink - “注意:这不是最新的可用版本”TestLink 上的错误
- javascript - Javascript 计数器变为 0 而不是给定的数字