Comment by dataflow
1 day ago
> Exceptions aren't meant to report errors, just in general. That's a misuse of them. Exceptions are meant to be thrown when a contract cannot be fulfilled. Yes, you're unable to know what exceptions a function may throw. That's the way it should be, because exceptions aren't supposed to be part of the function's contract.
I don't think these are true? What about std::vector::at(), std::optional::value(), etc.? And then there's std::system_error.
>std::vector::at(), std::optional::value()
Both functions must return T &. If the vector is not long enough, or the object is not set, then returning a T & is impossible. So we have a function that has already been called and which must return something valid, and cannot return something valid. The only two ways to resolve this contradiction is to throw, or to terminate.
(Well, you could also trigger undefined behavior like operator[]() and operator*(). No comment.)
>And then there's std::system_error.
And what am I supposed to conclude from the existence of a type?
I think you missed my point. I was referring to the fact that some of these standard exceptions are very much a part of the contracts of their respective functions. In fact, that's their entire point. This directly contradicts what you wrote.
You're using "contract" in a different sense than I did. When I said "contract" I was referring to the required state of the program when the function is called and the guaranteed state of the program when the function returns. By definition an exception cannot be part of the contract in this sense, because a call that throws does not return. This narrower sense of contract is critical, because the entire point of exceptions is to enable alternate control path when it'd otherwise be impossible, such as in the examples I gave above with overloaded operators and code with evolving requirements.
2 replies →
> The only two ways to resolve this contradiction is to throw, or to terminate.
Or they’re bad APIs that should be redesigned to be not bad.
They’re fallible functions. Don’t write fallible APIs that require exceptions to report errors! That’s bad API design!