I think that it's a truism that any function written in Python could raise any exception :-)
In practice, though, I think it is reasonable to say that functions will *typically* but not necessarily exclusively raise a certain set of exceptions.
What you seem to be describing is similar to Java's "Checked Exceptions", which are widely agreed to be an failure. Can you explain why this would be more successful?
The last thing I want to see is people being encouraged to write code like this:
def demo(arg)->Something: # Raises ValueError try: processing... except ValueError: raise except: # Any other unexpected error. raise ValueError('something unexpected')
just to ensure that the declared exception is correct. I haven't extensively used Java, but the way I understand it in Java you're meant to either handle every single exception that a function can
O 25/09/20 ás 07:37, Steven D'Aprano escribiu: throw, or explicitly throw anything you haven't handled. I do agree that such an approach wouldn't be great for Python. I don't think (but don't quote me on that) that introducing this idea of annotating exceptions would lead people to writing code like the above (in the same way introducing typing annotations didn't lead to people checking all function argument types in every function :-P ). After all, there wouldn't be any runtime checks to make sure you handled any raisable exceptions.
In the same vein as adding type annotations to code, I think it'd be very useful to have exception "raises" annotations, i.e. a way to annotate what exceptions a function raises. Again, like type annotations, it shouldn't be mandatory nor actually be enforced at runtime. It would purely serve as a feature that IDEs can make use of. How would an IDE make use of this? What I had in mind was that an IDE could use this information to show autocomplete options when writing except blocks. The other day I was writing some code like this:
An example of how it may look:
def divide(numerator: float, denominator: float) raises [ZeroDivisionError] -> float: return numerator / denominator If either argument is a subclass of float, this could raise any exception. I see! Well, the way I had it in mind, you'd only really annotate the exceptions you as a function implementer think are meaningful. It doesn't have to be an exhaustive list, just exceptions the callers of
import requests try: requests.get('https://python.org') except WhateverExceptionTheRequestsLibraryRaises: pass And I remember having to dive into the documentation of the library to figure out what exception was actually raised by this method, and what the base class of said exception was. Whereas, IMO, it would be a lot nicer to have a built-in way to know what exceptions may be raised by a function call. the function will (probably) want to handle.