3

How do I set the arguments when I create an exception? Where do I find the list of arguments available for each Exception subclass? What are the best practices?

For example, if I know that a file does not exist, how do I raise the FileNotFoundError(missing_file) exception?

This shows the list of members of the FileNotFoundError exception:

>>> [a for a in dir(FileNotFoundError) if a>'a']
['args', 'characters_written', 'errno', 'filename', 'filename2', 'strerror', 'winerror', 'with_traceback']

This shows that it is possible to set some of the arguments when creating an exception:

>>> FileNotFoundError(1,2,3,4,5).filename
3
>>> FileNotFoundError(1,2,3,4,5).filename2
5

And this shows that those arguments mean something:

>>> raise FileNotFoundError(1,2,3,4,5)
Traceback (most recent call last):
  File "<pyshell#8>", line 1, in <module>
    raise FileNotFoundError(1,2,3,4,5)
FileNotFoundError: [WinError 4] 2: 3 -> 5

So I know the arguments are there, can be set and can be used. But I couldn't find any documentation about it.

Tthe raise documentation, the FileNotFoundError documentation or this post don't talk about the exception arguments.

Community
  • 1
  • 1
stenci
  • 8,290
  • 14
  • 64
  • 104
  • Not a full answer, but there is a list of exceptions [here](https://docs.python.org/3/library/exceptions.html). – CasualDemon Aug 26 '15 at 14:34
  • @CasualDemon That is one of the links in my question – stenci Aug 26 '15 at 16:10
  • Ah, missed that thought it was just code block. Those members are actually defined in `OSError` (but not in `Exception` or `BaseException`), not just `FileNotFoundError`, and can be set and accessed as normal as [this](http://stackoverflow.com/questions/8978057/raising-builtin-exception-with-default-message-in-python) answer shows. – CasualDemon Aug 26 '15 at 16:30
  • 1
    @CasualDemon The `FileNotFoundError` in my question is just an example. I'm looking for a generic way to address all the arguments of all the built in exceptions. They are built in, documented, and yet no argument documentation. The 3rd answer on the post your refer to tries to address my answer, but only for `OSError` and without explanation of the arguments. – stenci Aug 26 '15 at 16:43

1 Answers1

1

Looking at the page you linked for FileNotFoundError, it does say that it's a subclass of OSError, which has signature

OSError(errno, strerror[, filename[, winerror[, filename2]]])

One could reasonably infer that the subclass constructor has the same signature.

user1071847
  • 633
  • 9
  • 20
  • See my 4th comment to the post – stenci Oct 17 '17 at 16:21
  • @stenci: you do raise a very good issue; I looked at the documentation myself, and I agree it's oddly sparse on this issue. If I find out more information I'll edit my answer. – user1071847 Oct 18 '17 at 19:33