While using any library there is a need to handle exceptions it raises. In 
ideal conditions author of library defines base exception and builds hierarchy 
of exceptions based on it. Moreover, all exceptions a library raises (including 
those that do not inherit its base exception) are documented and this 
information is kept up to date. Unfortunately, this is not always the case. 
Library authors are free to use the language exception mechanism in any way. So 
instead of using documented features of library as a black box, the user often 
has to plunge into the source code of a library itself and look for exceptions 
it could raise in order to be prepared for them.

The essence of my idea is simple and does not affects compatibility with 
existing code: to automatically define a magic attribute of module under the 
working name "__exception__" while importing any module. It can be used in 
usual way, for example:
>>> try:
...     any_module.anything
... except any_module.__ exception__:
...     ...

Here any exception an author of library raises can be handled. This way you can 
handle any exception that occurs in the library without even knowing what 
exceptions it can raise.

The important point is that only exceptions raised in library itself are 
handled. Those exceptions that can be raised in underlying libraries and so on 
through the dependency chain should be handled separately.

Developing this idea, it could be more universal mechanism that works not only 
with modules, but with any objects of the language. For instance:
>>> try:
...     any_function()
... except any_function.__ exception__:
...     ...
or
>>> try:
...     AnyClass.anything
... except AnyClass.__ exception__:
...     ...

It is important to understand the key difference between this mechanism and the 
capture of broad exception: only those exceptions are handled that are RAISED 
EXPLICITLY inside the object, while broad exception captures ANY exceptions 
that may occur in the object.

It seems to me this idea will help library users more correctly handle their 
exceptions if this is problematic. This will save time and make code more 
reliable.
_______________________________________________
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/7V47CTLUB7DNUFINYTAQWVDD22DQ4VZ5/
Code of Conduct: http://python.org/psf/codeofconduct/

Reply via email to