Exception Vs Assertion

Use assertions for internal logic checks within your code, and normal exceptions for error conditions outside your immediate code’s control.

Don’t forget that assertions can be turned on and off – if you care about things like argument validation, that should be explicit using exceptions. (You could, however, choose to perform argument validation on private methods using assertions, on the grounds that a violation at that point is due to an internal bug rather than an external error.)

Alternatively it’s entire reasonable (IMO) to use exceptions for everything. I personally don’t use assertions much at all, but it’s a matter of personal preference to some extent. (There can certainly be objective arguments for and against assertions, but it’s not sufficiently clear cut to remove preference altogether.)

Leave a Comment