Is there a programmatic way to get a list of all exceptions a function could raise?
I know for example that os.makedirs(path[, mode])
can raise PermissionError
(and maybe others), but the documentation only mentions OSError
. (This is just an example - maybe even a bad one; I am not especially interested in this function - more in the problem in general).
Is there a programmatic way to find all the possible exceptions when they are not/poorly documented? This may be especially useful in 3rd-party libraries and libraries that do not ship with Python source code.
The solution presented in "Python: How can I know which exceptions might be thrown from a method call" does not work in Python 3; there is no compiler
package.
Finding Exception in non built-in source code:
As said in the topic Python: How can I know which exceptions might be thrown from a method call, you can get the Abstract Syntax Tree and search for raised exceptions.
This method works for every piece of code that you have written.
Finding Exception in Built-in methods
You cannot parse built-in function like
os.makedirs
.Two alternatives:
For all native C methods, you are stuck with the documentation and should trust it. When
os.makedirs
says it only returnsOSError
, it is true, sincePermissionError
andFileExistError
exceptions are subclasses ofOSError
.To find Errors programmatically for built-in you can use this example:
It catches all exceptions with a name ending with 'Error', it surely can be extended to find all standard exceptions.
You can't get reliable results for some (if not most) functions. Some examples:
functions that execute arbitrary code (e.g.
exec(')(rorrEeulaV esiar'[::-1])
raisesValueError
)functions that aren't written in Python
functions that call other functions that can propagate errors to the caller
functions re-raising active exceptions in the
except:
blockUnfortunately, this list is incomplete.
E.g.
os.makedirs
is written in Python and you can see its source:Bare
raise
re-raises the last active exception (OSError
or one of its subclasses). Here's the class hierarchy forOSError
:To get the exact exception types you'll need to look into
mkdir
, functions it calls, functions those functions call etc.So, getting possible exceptions without running the function is very hard and you really should not do it.
However for simple cases like
a combination of
ast
module functionality andinspect.getclosurevars
(to get exception classes, was introduced in Python 3.3) can produce quite accurate results:prints
Keep in mind that this code only works for functions written in Python.