Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Catch exception throw from inside of the with statement

Tags:

python

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?

like image 953
q0987 Avatar asked Feb 22 '23 17:02

q0987


2 Answers

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.

like image 135
Chris Phillips Avatar answered Mar 06 '23 22:03

Chris Phillips


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.

like image 45
Mark Byers Avatar answered Mar 06 '23 23:03

Mark Byers