Platform Independent Exception Handling

Consider the following Python exception:

[...] f.extractall() File "C:\Python26\lib\zipfile.py", line 935, in extractall self.extract(zipinfo, path, pwd) File "C:\Python26\lib\zipfile.py", line 923, in extract return self._extract_member(member, path, pwd) File "C:\Python26\lib\zipfile.py", line 957, in _extract_member os.makedirs(upperdirs) File "C:\Python26\lib\os.py", line 157, in makedirs mkdir(name, mode) WindowsError: [Error 267] The directory name is invalid: 'C:\\HOME\\as\ \pypm-infinitude\\scratch\\b\\slut-0.9.0.zip.work\\slut-0.9\\aux' 

I want to handle this specific exception - that is, a WindowsError with error number 267. However, I cannot just do the following:

 try: do() except WindowsError, e: ... 

Because this will not work on Unix systems where WindowsError is not even defined in the exception module.

Is there an elegant way to handle this error?

+6
python windows exception exception-handling
source share
3 answers

Here is my current solution, but I despise the use of non-trivial code in the exception block a bit:

  try: f.extractall() except OSError, e: # http://bugs.python.org/issue6609 if sys.platform.startswith('win'): if isinstance(e, WindowsError) and e.winerror == 267: raise InvalidFile, ('uses Windows special name (%s)' % e) raise 
+4
source share

If you need to catch an exception with a name that may not always exist, create it:

 if not getattr(__builtins__, "WindowsError", None): class WindowsError(OSError): pass try: do() except WindowsError, e: print "error" 

If you are running Windows, you will use the real WindowsError class and catch the exception. If you do not, you will create a WindowsError class that will never be raised, so the except clause will not cause any errors, and the except clause will never be called.

+12
source share
Answer to

@Glenn Maynard does not allow debugging using pdb, since the built-in WindowsError is not available in the debugger. This code block will work inside the Python debugger and in normal execution:

 import exceptions if not getattr(exceptions, "WindowsError", None): class WindowsError(OSError): pass 

This solution also works and avoids string literals and imports a complete exception library:

 try: from exceptions import WindowsError except ImportError: class WindowsError(OSError): pass 
0
source share

All Articles