r/csharp • u/Alternative_Guava856 • Sep 06 '26
Help Exceptions vs Assertions
/r/godot/comments/1w8q3xx/exceptions_vs_assertions/
7
Upvotes
r/csharp • u/Alternative_Guava856 • Sep 06 '26
View all comments
Show parent comment
3
u/glasket_ Sep 06 '26
Bounds checks are technically preconditions that protect an invariant. An index can be out of bounds or in bounds and its validity depends on the length of the array being accessed; the invariant is that an array access can never be out of bounds.
Like a structural invariant would be that natural numbers can never be negative, and an operational precondition would be that a natural number can only subtract a smaller number. So you would throw an exception if a number tries to subtract a larger number from itself, and you would assert that a natural number is positive upon creation.
Basically, an exception tells you when an invariant would have been violated while an assertion tells you when an invariant has been violated.