2 ms·
Absolutely. Whether a method throws or not signals the intent of the code. In .NET, there are plenty of throwing and non-throwing versions of various methods.
by wvenable 7y ago
Absolutely. Whether a method throws or not signals the intent of the code. In .NET, there are plenty of throwing and non-throwing versions of various methods. For example, there are both Parse() and TryParse() and also First() and FirstOrDefault() in Linq. Which method you use signals to the reader the expected result. If you're using Parse() then you're expecting the parse to succeed; Perhaps the data comes from a data file and if it's not an integer then something terrible has happened. Alternatively, you would use TryParse() for user input knowing that users will definitely not be trusted to always type a number.
Not having non-throwing versions of these methods (e.g. Java) means you lose the ability to signal intent and you have to do a lot of pointless catching of exceptions.
- TheSoftwareGuy 7y agoOn the other hand, if you are writing library code or even a library-ish component of application code, having to write the same method a bunch of different times is tedious. Ideally, the language would be designed so that there is one sane way of propagating errors, which can be easily either handled or propogated. I am quite a fan of Rust's solution, with Result<T> types and various macros/methods which can do the commmon stuff for you
- wvenable 7y agoIn this case, it's the difference between what is an is not an error. Only one of those situations is an error. I agree having to write the same method a bunch of times is tedious but that is usually not the case. Most situations have clear intentions. It's much more likely in framework APIs where there are a bunch of non-task-specific operations. I find the whole manual propagation of errors, even with a lot of helpers, to just be tedious boilerplate. Most of the time I literally don't care about the error -- I want to crash my app, log the error, and alert me and the user. I don't need to propagate the potentially limitless number of errors possible in any non-trivial application.
- noisem4ker 7y agoIn Java, you can obtain a throwing version of anything returning an Optional type: Optional<Womp> getWomp() {...} Womp womp = getWomp().orElseThrow();