C has perror and errno, which print and store the last error encountered. This is convenient when doing file io as I do not have to fstat() every file that fails as an argument to fopen() to present the user with a reason why the call failed.
I was wondering what is the proper way to grab errno when gracefully handling the IOError exception in python?
In [1]: fp = open("/notthere") --------------------------------------------------------------------------- IOError Traceback (most recent call last) /home/mugen/ in () IOError: [Errno 2] No such file or directory: '/notthere' In [2]: fp = open("test/testfile") --------------------------------------------------------------------------- IOError Traceback (most recent call last) /home/mugen/ in () IOError: [Errno 13] Permission denied: 'test/testfile' In [5]: try: ...: fp = open("nothere") ...: except IOError: ...: print "This failed for some reason..." ...: ...: This failed for some reason...
It is an error raised when an input/output operation fails, such as the print statement or the open() function when trying to open a file that does not exist. It is also raised for operating system-related errors.
IOError in Python is a result of incorrect file name or location. This error is raised in multiple conditions and all these conditions can be handled using try except code block.
In Python, exceptions can be handled using a try statement. The critical operation which can raise an exception is placed inside the try clause. The code that handles the exceptions is written in the except clause. We can thus choose what operations to perform once we have caught the exception.
errno. EEXIST. File exists. This error is mapped to the exception FileExistsError .
The Exception has an errno
attribute:
try: fp = open("nothere") except IOError as e: print(e.errno) print(e)
Here's how you can do it. Also see the errno
module and os.strerror
function for some utilities.
import os, errno try: f = open('asdfasdf', 'r') except IOError as ioex: print 'errno:', ioex.errno print 'err code:', errno.errorcode[ioex.errno] print 'err message:', os.strerror(ioex.errno)
For more information on IOError attributes, see the base class EnvironmentError:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With