3 ms·
In .NET, they have 2 sets of parsing functions, "Parse" and "TryParse" for parsing strings into other types. The first throws an exception if it can't parse an
by wvenable 2y ago
In .NET, they have 2 sets of parsing functions, "Parse" and "TryParse" for parsing strings into other types. The first throws an exception if it can't parse and the second returns a Boolean indicating success or failure.
Which function of these you use as a programmer is dependent on the context and it indicates your expectation. You might use "Parse" if you reading a well-defined file format where the string will always contain an integer and if it doesn't then something has gone horribly wrong. But you might use "TryParse" on user input where getting a non-integer is expected and you'll have to something about that other than error out.
- erik_seaberg 2y agoWas this a workaround for frequent exception handling being too expensive on some platform? I like how Java lets some exception instances be reused without stack frames, so performance issues are less likely to compromise API design.
- wvenable 2y agoSemantically I think it's great. .NET has a bunch of these especially in LINQ. A parsing failure isn't necessary an error. Sometimes it is, sometimes it's not. Even if exceptions weren't expensive, catching exceptions on all parsing (as you would in Java) is just ugly and, I would argue, not semantically correct. In my opinion, one should throw often but catch infrequently. Most of my large applications have a very small number of catches. It's also perfectly reasonable to move this down a layer and have Parse return an Option type and choose to handle did-not-parse case or don't and let that trigger an exception.
- jkrejcha 2y agoIt, according to Eric Lippert, was at least partially to fix the problem of vexing exceptions[1] that plagued Int32.Parse. Parse was first and it was kind of an unfortunate design decision to make a almost expected result (parsing to fail) throw an exception. It's worth noting that nowadays Parse is just a wrapper around TryParse that throws (although this is an implementation detail) [1]: https://ericlippert.com/2008/09/10/vexing-exceptions/ https://ericlippert.com/2008/09/10/vexing-exceptions/
- winstonewert 2y agoI think the causation runs in the opposite direction. These exceptions for these platforms were implemented in an inefficient fashion BECAUSE they thought that exceptions should almost never be thrown.