我是一名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
以这种方式实现的想法是捕获所有不同场景的确切错误。我可以在所有单独的try
/ except
块中执行此操作。
这可能吗?合理吗?
答案 0 :(得分:4)
您的try
块应该尽可能小,所以
try:
# do all
except Exception:
pass
不是你想做的事。
您示例中的代码无法按预期工作,因为在每个except
块中,您捕获的是最常见的异常类型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()
但是,有时在同一个except
块或几个块中捕获不同类型的异常是合适的。
try:
ssh.connect()
except (ConnectionRefused, TimeoutError):
pass
或
try:
ssh.connect()
except ConnectionRefused:
pass
except TimeoutError:
pass
答案 1 :(得分:0)
是的,这是可能的。
就这样说:
try:
...
except RuntimeError:
print err1
except NameError:
print err2
...
只需定义要拦截的确切错误。
答案 2 :(得分:0)
如DeepSpace所述,
您的
try
块应该尽可能小。
如果你想实现
try:
# do all
except Exception:
pass
然后你可以做一些像
这样的事情def open_file(file):
retval = False
try:
# opening the file succesful?
retval = True
except FileNotFoundException:
print('File does not exist')
except PermissionError:
print('You have no permission.')
return retval
def crunch_file(file):
retval = False
try:
# conversion or whatever logical operation with your file?
retval = True
except ValueError:
print('Probably wrong data type?')
return retval
if __name__ == "__main__":
if open_file(file1):
open(file1)
if open_file(file2) and crunch_file(file2):
print('opened and crunched')