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.
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.
Is it ok to use lots of
try
s instead of even moreif
s?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With