zip_file_name = "not_exist.py"
try开发者_高级运维:
with zipfile.ZipFile(zip_file_name) as f_handle:
print("open it successfully")
except (zipfile.BadZipfile, zipfile.LargeZipFile), e:
print(e)
Is this the correct way to handle exception throw by a with statement?
Yes, this is how you would want to handle exceptions from inside a with
statement. ContextManagers (that implement the behavior behind the with
statement) can handle exceptions but should only do so to properly clean up resources used by the object.
Here's a snippet from the relevant documentation:
If BLOCK raises an exception, the context manager’s exit() method is called with three arguments, the exception details (type, value, traceback, the same values returned by sys.exc_info(), which can also be None if no exception occurred). The method’s return value controls whether an exception is re-raised: any false value re-raises the exception, and True will result in suppressing it. You’ll only rarely want to suppress the exception, because if you do the author of the code containing the ‘with‘ statement will never realize anything went wrong.
Yes, that's fine.
Another alternative is:
try:
f_handle = zipfile.ZipFile(zip_file_name)
# no more code here
except (zipfile.BadZipfile, zipfile.LargeZipFile), e:
print(e)
else:
with f_handle:
print("open it successfully")
This prevents you from accidentally catching an exception from the body of the with
statement in your except
handler.
精彩评论