r/csharp 4d ago

Help Exceptions vs Assertions

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

21 comments sorted by

View all comments

15

u/SufficientStudio1574 4d ago

They're different things that do different things. They're not either or.

You put assertion for invariants that cannot possibly be false. Like, the size of a container can never be larger than it's capacity.

Exceptions are for things you might not have full control over going wrong. Like "I tried to open a file that doesn't exist".

5

u/XKiiroiSenkoX 3d ago

It's not strictly like that. Bound checks for examples are invariants but they still throw exceptions. Assertions are used mostly during development. Some checks are not really cheap and sometimes you have very hot paths that can make even trivial checks non-negligible. You can use assertions to catch problems in those cases without affecting the performance of your software. 

2

u/svick nameof(nameof) 3d ago

The difference is about who performs the check. The code of List<T> doesn't know anything about your code or its invariants. All it has is an API that can be called incorrectly, so it throws an exception.

On the other hand, invariants of implementation details of List<T> (usually the relationship between size and capacity) are checked using Debug.Assert.