Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Try/Catch Use Convention(s)

What is the convention for Try/Catch outside of obviously needed locations(such as getting specific user input)? While code re-use is an important idea behind OOP, is it expected that each (example) array access should have a try/catch? Is it primarily the designer's decision of what can throw an exception, and those parts of the program that should be well regulated enough to never throw an exception?

Ex. An array of playing cards is, and should always be, 52 cards. No try/catch is necessary. Or since an array out of bounds exception could cause a run-time error, and the deck could be used at a later date with jokers added, then put it in now?

like image 368
Volvox Avatar asked Dec 02 '22 00:12

Volvox


2 Answers

You should only catch exceptions, you can actually handle. I.e. you should not have try/catch statements everywhere.

As for throwing exceptions, you should throw an exception when there's no better option. If you can handle user input meaningfully then there's no reason to throw an exception in that case. Without knowing the specifics I would assume that there's no need for an exception in this case.

like image 145
Brian Rasmussen Avatar answered Dec 04 '22 13:12

Brian Rasmussen


Your example is a little off.

Assuming you have an array of 52 elements, the correct way of handling this is to test that your index is within the bounds of the array before even attempting to access it. This is far better than simply wrapping the code in a try .. catch in there.

Try Catch is there to help save us from ourselves. If a given method is coded properly then there is very little reason to use them. By properly I mean that you verify your inputs are within the ranges expected and you've tested enough to know that the code won't "except" out. Of course, an example of "very little" include calls to unmanaged resources such as the SqlConnection object.

Point is, it's a crutch that is a last ditch effort to salvage something usable out of that particular code blocks execution.

If, however, there is literally nothing that can be done about the exception then I'd say your only choices are to ignore it and let it bubble up or catch, log and rethrow.

like image 35
NotMe Avatar answered Dec 04 '22 12:12

NotMe