Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to specify Exception arguments in python?

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.

like image 891
stenci Avatar asked Nov 20 '25 14:11

stenci


1 Answers

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.

like image 196
user1071847 Avatar answered Nov 24 '25 22:11

user1071847



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!