首页 > 解决方案 > 如何在一个“尝试”块中引发同一错误的多个异常

问题描述

我正在创建一个程序,可让您从 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 块中引发两个相同的异常?

标签: python-3.xtry-catch

解决方案


for exe in ['chrome.exe','firefox.exe','msedge.exe']:
    try:
        os.startfile(exe)
        break

    except FileNotFoundError:
        print(exe,"error")

推荐阅读