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
withstatement. ContextManagers (that implement the behavior behind thewithstatement) 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: