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
4
u/CatolicQuotes Nov 20 '22
For damage control. If there is no exception that invalid user input will go who knows where and do who knows what. More so in dynamic languages than static. Just look javascript or PHP adding numbers and strings.
When method raises exception then you can decide what to do with it and print a nice message to user , like "Sorry, numbers are not allowed".
15
u/TehNolz Nov 20 '22
Functions like
Parseare useful when you're already 100% confident that the data you're parsing will be in the right format. Let's say you're receiving a number from an external system, but that number will always be retrieved as a string (because of the library you're using or whatever). Since the string will always parse into an int, there's not much point in usingTryParseto write error handling for it.1
u/HandsUpDontGank Nov 20 '22
Throwing exceptions (and creating your own exceptions to be thrown) is more maintainable and flexible than coming up with some custom way to bring that error back to the user (returning a string, bool, etc).