如何处理多个异常?

Use*_*ser 3 python python-2.7

我是 Python 学习者,尝试处理一些场景:

  1. 读取文件。
  2. 格式化数据。
  3. 操作/复制数据。
  4. 写文件。

到目前为止,我有:

try:
   # Do all
except Exception as err1:
   print err1
   #File Reading error/ File Not Present

except Exception as err2:
   print err2
   # Data Format is incorrect
except Exception as err3:
   print err3
   # Copying Issue
except Exception as err4:
   print err4
   # Permission denied for writing
Run Code Online (Sandbox Code Playgroud)

以这种方式实现的想法是捕捉所有不同场景的确切错误。我可以在所有单独的try/except块中做到这一点。

这可能吗?并且合理?

Dee*_*ace 10

  1. 你的try块应该尽可能小,所以

    try:
         # do all
    except Exception:
         pass
    
    Run Code Online (Sandbox Code Playgroud)

    不是你想做的事情。

  2. 您示例中的代码不会像您期望的那样工作,因为在每个except块中您都会捕获最常见的异常 type Exception。事实上,只有第一个except块会被执行。

您想要做的是拥有多个try/except块,每个块负责尽可能少的事情并捕获最具体的异常。

例如:

try:
    # opening the file
except FileNotFoundException:
    print('File does not exist')
    exit()

try:
   # writing to file
except PermissionError:
   print('You do not have permission to write to this file')
   exit()
Run Code Online (Sandbox Code Playgroud)

但是,有时在同except一块或多个块中捕获不同类型的异常是合适的。

try:
    ssh.connect()
except (ConnectionRefused, TimeoutError):
    pass
Run Code Online (Sandbox Code Playgroud)

或者

try:
    ssh.connect()
except ConnectionRefused:
    pass
except TimeoutError:
    pass
Run Code Online (Sandbox Code Playgroud)

  • 唱反调:我们不是从显式错误处理飞跃到异常(特别是)在堆栈中冒泡,以获得创建更大的“try”块并将错误处理集中在其他地方的能力吗? (2认同)