Python cant handle exceptions from zipfile.BadZipFile
<p>Need to handle if a zip file is corrupt, so it just pass this file and can go on to the next.</p>

<p>In the code example underneath Im trying to catch the exception, so I can pass it. But my script is failing when the zipfile is corrupt*, and give me the "normal" traceback errors* istead of printing "my error", but is running ok if the zipfile is ok.</p>

<p>This i a minimalistic example of the code I'm dealing with.</p>

<pre><code>path = "path to zipfile" 

from zipfile import ZipFile

with ZipFile(path) as zf:
    try:
        print "zipfile is OK"
    except BadZipfile:
        print "Does not work "
        pass
</code></pre>

<p>part of the traceback is telling me: raise BadZipfile, "File is not a zip file"</p>

<p>You need to put your context manager <em>inside</em> the <code>try-except</code> block:</p>

<pre><code>try:
    with ZipFile(path) as zf:
        print "zipfile is OK"
except BadZipfile:
    print "Does not work "
</code></pre>

<p>The error is <em>raised by</em> <code>ZipFile</code> so placing it outside means no handler can be found for the raised exception. In addition make sure you appropriately import <code>BadZipFile</code> from <code>zipfile</code>.</p>

python python-2.7 exception-handling zipfile