【问题标题】:multiple try catch blocks in a loop循环中的多个 try catch 块
【发布时间】:2017-01-24 09:57:18
【问题描述】:

我做这样的事情是不是很愚蠢?我觉得我可能无法从根本上理解try catch 块的目的。

我有一个脚本,我想在守护进程上自动运行,有时会检查列表中的某些资源是否已完全分配。如果资源被完全分配,它不能继续做一件事,但它可以做其他事情。因为我也是从 API 调用某些东西,所以有时 API 抛出的 Exception 非常通用(就像 API_Exception 一样)。在这种情况下做多个 try 块毫无意义吗?

主要问题是break 不允许我跳出循环

for:
    try: 
         stuff()
    except ExceptionA:
         handle()
         break
    except ExceptionB:
         report()
         sys.exit()
    try:
         other_stuff()
    except ExceptionA:
         handle_in_a_different_way()
         break
    except ExceptionC:
         report()
         sys.exit()

other_code_that_should_execute_if_there_is_a_break()

在这种情况下,我是否应该将这两个块组合起来并捕获一次ExceptionAExceptionA 可能没有容易解析的参数。

for:
    try:
        stuff()
        other_stuff()
    except ExceptionA:
        if ExceptionA has param
            handle()
        elif ExceptionA has other param
            handle_in_a_different_way()
    except ExceptionB:
        report()
        sys.exit()
    except ExceptionC:
        report()
        sys.exit()

【问题讨论】:

  • 在后一种情况下,您可以将except (ExceptionB,ExceptionC): 分组。

标签: python loops exception


【解决方案1】:

我在异常方面不是很有经验,但我在堆栈中发现了一些可能有用的东西。

Catch multiple exceptions in one line (except block)

这还取决于您当前使用的版本,在 python 2 中,您似乎可以使用逗号分隔异常,但在 python 3 中,人们建议使用 'as' 将它们设置在变量中,然后您可以验证如何对待他们

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-06-08
    • 1970-01-01
    • 1970-01-01
    • 2013-05-27
    • 1970-01-01
    • 1970-01-01
    • 2017-08-31
    相关资源
    最近更新 更多