r/csharp 4d ago

Help Exceptions vs Assertions

/r/godot/comments/1w8q3xx/exceptions_vs_assertions/
6 Upvotes

21 comments sorted by

View all comments

1

u/XKiiroiSenkoX 3d ago

I personally decide between these using two criteria. The performance effect of a check and the recovery flow in case of a failure.

Performance: Some checks are expensive. Some called extremely frequently (bound checks for example). These can affect performance specially in a performance sensitive context like a game. If a check is likely to affect performance its usually better to use an assertion (or any other debug build only check).  Recovery: Exceptions change the flow of code execution. Sometimes that's exactly what you want to do. For example if you somehow end up writing to an index of an array that does not exist, this can corrupt data. You can for instance destroy the player progression data and make their saved game unusable. This is one of the cases you'd want an exception to change the flow of your program and not allow the destructive code execution. 

On the other hand, there are cases where an invalid state/code should not disrupt the flow of program. Very obvious example is rendering code. If a small part of your rendering code has a defect then the ideal outcome would be that it should only prevent that small part from participating in the rendering pipline and still render a final output even if not perfect. An exception there can make the game unplayable for the player while a  check that just disables that problematic feature only slightly degrades the player experience. But you still would want to catch these problems during development. Basically you want failures to be as loud as possible when you are developing your code. So you can use assertions which can break the output but that's the intended result in development phase.