There is a fundamental misunderstanding here. You are right that only the caller can know whether it can handle the exception. A type checker’s job in this scenario would not be to know whether the caller can handle the exception but just to note whether or not the caller did catch the exception. If the caller did not then the exception would be propagated so a checker can infer that the caller potentially raises that exception as well.
Yes although the important part missing here is that it should not be necessary to add an explicit “raises” annotation to indicate that uncaught exception would be propagated. The checker could infer that an uncaught exception would be propagated because that is what uncaught exceptions do and it is easy for the checker to model that behaviour. See e.g.:
There very clearly is a difference between one exception type and another. Exceptions are caught based on their type so raising a different exception type than was documented and expected by the caller is incorrect behaviour that can lead to breakage. There will be code that catches the expected exception types e.g.:
while True:
string = input("Enter a number:")
try:
number = int(string)
except ValueError:
print("Invalid number. Try again...")
If there was a proposal to change the exception type that is raised by int(string)
to a new exception like say ParseError
then that proposal would rightly be rejected for being backwards incompatible. There are good reasons to catch the ValueError
and the caller needs to know what exception type to catch. Changing that exception type would break downstream code.
What this shows is that the type of the exception that is raised is part of the interface of the function and that the type definitely does matter (this is exactly why exceptions have types in the first place). The fact that the type of the exception matters means that it is useful to be able to document what that exception type is and also that it would be useful to be able to check that the actual code matches what it claims to raise.