Exception Vs Assertion

JavaResp picture JavaResp · Aug 14, 2009 · Viewed 39.7k times · Source

What is the difference between Java exception handling and using assert conditions?

It's known that Assert is of two types. But when should we use assert keyword?

Answer

Jon Skeet picture Jon Skeet · Aug 14, 2009

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.)