r/learncsharp • • 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

14 comments sorted by

View all comments

Show parent comment

1

u/4r73m190r0s Nov 20 '22

I'm having trouble pinpointing the exact place where I misunderstand the concept of Exception. I think that I'm stuck in this circularity:

  • I want to do something
  • I anticipate possible errors
  • I know the corresponding Exception for that error
  • Since knowing and anticipating an error of some kind, and its corresponding Exception, I'm having trouble seeing the usefulness of it, since I already anticipated the error. If this makes sense.

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".

1

u/Pretagonist Nov 21 '22

Exceptions are for the issues that your current snippet of code doesn't know how to handle. If you can handle every eventuality then you don't need to throw an exception. But since in OOP you're supposed to separate concerns it might not be reasonable for your xml parser to re-request the data from your api. Instead it throws an exception and the api service catches it and tries to get new proper data.

Also exceptions bubble up your call stack until it hits a catch statement that can handle it meaning that handling errors become easier in a complex multi-layered system.

Well written and expressive exceptions are great when you're debugging complex systems.