如何在一个“ Try”块中引发同一错误的多个异常

时间:2020-08-06 18:16:08

标签: python-3.x try-catch

我正在创建一个程序,可让您从Python启动应用程序。我进行了设计,因此,如果未下载某个Web浏览器,它将默认使用另一个浏览器。不幸的是,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块中引发两个相同的异常?

2 个答案:

答案 0 :(得分:1)

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

    except FileNotFoundError:
        print(exe,"error")

答案 1 :(得分:0)

对于您的确切情况,我建议这样做:

priority_apps = ['chrome.exe', 'firefox.exe', 'msedge.exe']  # attempts to open in priority order
current_priority = 0
opened_app = False
while not opened_app and current_priority < len(priority_apps):
    try: 
        os.startfile(priority_apps[current_priority])
        opened_app = True
    except Exception as e:
        current_priority += 1
if not opened_app:
    print("couldn't open anything! :(")

具有功能的通用替代方法:

try:
    do_something()
except Exception as e:
    do_something_else1()

def do_something_else1():
    try:
        do_something()
    except Exception as e:
        do_something_else2()

具有嵌套try / except的通用替代项:

try: 
    do_something()
except Exception as e: 
    try: 
        do_something_else()
    except Exception as e:
        do_something_better()