I'm trying to implement a method that returns an error whenever a certain directory does not exist.
Rather than doing raise OSError("Directory does not exist.")
, however, I want to use the builtint error message from OSError: OSError: [Errno 2] No such file or directory:
. This is because I am raising the exception in the beginning of the method call, rather than later (which would invoke the same message from python, without any necessary raise
).
Any pointers? (other than manually doing OSError("[Errno 2] No such file or directory: ")
)
As a Python developer you can choose to throw an exception if a condition occurs. To throw (or raise) an exception, use the raise keyword.
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.
This exception is derived from RuntimeError . It is raised when the interpreter detects that the maximum recursion depth (see sys.getrecursionlimit() ) is exceeded. New in version 3.5: Previously, a plain RuntimeError was raised.
import os try: open('foo') except IOError as err: print(err) print(err.args) print(err.filename)
produces
[Errno 2] No such file or directory: 'foo' (2, 'No such file or directory') foo
So, to generate an OSError
with a similar message use
raise OSError(2, 'No such file or directory', 'foo')
To get the error message for a given error code, you might want to use os.strerror
:
>>> os.strerror(2) 'No such file or directory'
Also, you might want to use errno
module to use the standard abbreviations for those errors:
>>> errno.ENOENT 2 >>> os.strerror(errno.ENOENT) 'No such file or directory'
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