Issue
I was playing around with python, and I was trying to open a file. I accidentally made a typo, and got the expected error:
FileNotFoundError: [Errno 2] No such file or directory: 'tlesting.py'
It was supposed to be testing.py
if you are wondering.
Of course, I expected the error, but I want to know the reason behind why [Errno 2]
is included. I got curious, so I tried raising the error myself: raise FileNotFoundError("This is a test")
, and got an output of: FileNotFoundError: This is a test
, but no [Errno 2]
anymore. Is this something to do with the current version of python or my current operating system?
Solution
To add the [Errno 2]
tag, you can pass the appropriate error number as an explicit first argument:
>>> import errno
>>> raise FileNotFoundError("foo")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
FileNotFoundError: foo
>>> raise FileNotFoundError(errno.ENOENT, "foo")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
FileNotFoundError: [Errno 2] foo
Answered By - chepner
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.