How to handle OSError: [Errno 36] File name too long
Solution 1
Simply check errno
attribute of caught exception.
try:
do_something()
except OSError as exc:
if exc.errno == 36:
handle_filename_too_long()
else:
raise # re-raise previously caught exception
For readability you may consider using appropriate constant from errno
built-in module instead of hardcoded constant.
Solution 2
You can specify just how you want to catch a specific error such as errno.ENAMETOOLONG:
Specific to your question...
try:
# try stuff
except OSError as oserr:
if oserr.errno != errno.ENAMETOOLONG:
# ignore
else:
# caught...now what?
Specific to your comments...
try:
# try stuff
except Exception as err:
# get the name attribute from the exception class
errname = type(err).__name__
# get the errno attribute from the exception class
errnum = err.errno
if (errname == 'OSError') and (errnum == errno.ENAMETOOLONG):
# handle specific to OSError [Errno 36]
else if (errname == 'ExceptionNameHere' and ...:
# handle specific to blah blah blah
.
.
.
else:
raise # if you want to re-raise; otherwise code your ignore
This will grab all exceptions caused by errors in the try
. Then it checks if the __name__
matches any specific exception and any additional conditions you want to specify.
You should know there is no getting around the except
if an error is encountered unless you specific a concrete exception.
Max Matti
Currently working at fodjan GmbH in Dresden, nothing spectacular to see here.
Updated on June 13, 2020Comments
-
Max Matti almost 4 years
When handling the errors that occur when trying to create an existing file or trying to use a file that doesn't exist the
OSError
s that get thrown have a subclass (FileExistsError
,FileNotFoundError
). I couldn't find that subclass for the special case when the filename is too long.The exact error message is:
OSError: [Errno 36] File name too long: 'filename'
I would like to catch the OSError that occurs when the filename is too long, but only when the filename is too long. I do not want to catch other
OSError
s that might occur. Is there a way to achieve this?Edit: I know that I could check the filename against a length but the maximum filename length varies too much depending on the OS and the filesystem and I don't see a "clean" solution that way.