我是 Python 学习者,尝试处理一些场景:
到目前为止,我有:
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
你的try块应该尽可能小,所以
try:
# do all
except Exception:
pass
Run Code Online (Sandbox Code Playgroud)
不是你想做的事情。
您示例中的代码不会像您期望的那样工作,因为在每个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)
| 归档时间: |
|
| 查看次数: |
11148 次 |
| 最近记录: |