try catch needed? Or recommended?
I am just recently learning about exception handling and I have yet to come across an example where Try catch was the only way to handle the error. Everything else we have come across we could use some sort of manual while loop condition to keep the user from screwing up. I am just wondering where try catch is needed and while loop will not suffice, as well as what are the advantages of try catch over using your own special way of handling the user input. Is it just to keep the code readable and pleasant to the eye?
Re: try catch needed? Or recommended?
The general rule is that, if you can avoid a try-catch using checks (ifs etc.) before an exception would be thrown, do it. Exceptions do have an additional cost to them when compared with pre-checks. However, sometimes Exceptions are unavoidable. When defining APis, exceptions help enforce the rules of that API. As no API can predict every situation their library will be put through, exceptions are added into method signatures to tell clients, if they break the rules, I will not accept it and I will throw an error/exception.
Ask yourself, should the performance for every client take a hit by doing all these checks on the off chance that a client makes a mistake? or should they leave that stuff the the developer? the latter makes more sense.