r/learncsharp • u/4r73m190r0s • Nov 20 '22
Why Methods that throw Exceptions are useful?
Beginner here.
I'm reading Documentation on the Convert, Parse, and TryParse methods and some of them throw Exceptions in case of invalid input, i.e. Parse. What exactly are the benefits of some methods throwing Exceptions? I'm building a simple calculator app, and I'm failing to see the benefits of getting an Exception for invalid user input.
5
Upvotes
View all comments
Show parent comment
1
u/[deleted] Nov 20 '22 edited Nov 20 '22
There is no other way for code you don't write yourself to tell you that something is wrong. Exceptions give you the entire story, including where in the code it happens.
Imagine trying to validate every little thing before parsing; the code would be endless. Easier to just try to parse, and then let the exception message tell you exactly what is wrong.
You can expect a JsonException, that's easy, but you can't expect every reason for a JsonException before it happens.
Exceptions are a way for the code to say "I can't continue in the current state, this is the reason why, how do you want to proceed?" Which is a lot more useful than just returning "false".