Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it ok to use lots of `try`s instead of even more `if`s?

In my game, there are many things checked and often the indexes are out of bounds, and it's usually ok if sometimes things are not drawn or checked for. Currently my code is easy enough to read, though when debugging, the game loses a frame or two because of the exceptions that are being logged. It works fine outside the VS though. When I tried to avoid exceptional situations using lots and lots of if statements, it greatly decreased code readability and removed the low fps loss. I wonder if it has any other effects.

like image 693
user1306322 Avatar asked Dec 12 '22 00:12

user1306322


2 Answers

Throwing exceptions is very resource intensive- it is vastly faster to use if/then statements or other "normal" flow control.

Exceptions are mainly expensive because generating the Exception instance requires a stack walk has to be performed to figure out where the exception was thrown (the stack trace). It also creates extra load for the Garbage Collector, and is considered very poor design to use exceptions outside of exceptional situations.

like image 194
Chris Shain Avatar answered Jan 07 '23 23:01

Chris Shain


Is it ok to use lots of trys instead of even more ifs?

If you need either of these to have a functional application, then something may be wrong with your design. Exceptional situations are generally supposed to be exceptional, not commonplace.

The situations you described (indices out of bounds) are clearly not exceptional, especially since you ignore the exceptions because it's not a big deal. That's a big hint that you should be investing the effort into preventing the exceptions from happening in the first place.

When I tried to avoid exceptional situations using lots and lots of if statements ...

Lots of if statements is not a good approach, as you discovered -- it's hard to read, and it may hide logic errors, which just creates more headaches.

Instead, consider giving your objects more clearly defined and discrete responsibilities, to prevent them from entering states that might be exceptional to begin with. If you need "lots and lots" of if statements, then your objects are checking many conditions, which means their responsibilities are probably too big.

like image 35
John Feminella Avatar answered Jan 07 '23 21:01

John Feminella