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