views:

442

answers:

4

Are there any situations when you would use assertion instead of exceptions-handling inside domain classes...

+3  A: 

Never. Assertions are not a valid form of error-handling. Use them to assist in identifying program errors during testing.

Shog9
A: 

Are not assertions usually turned off for live as well?

willcodejavaforfood
+3  A: 

Use exceptions for parameter validation and other checks which verify that the users of you classes use them as intended.

Use assertions for internal consistency checks, i.e. to indicate you screwed up, not the user of your class.

Thus, if users of your class see an assertion failure, they know it is (probably) an internal error in your code, not in their use of your code. On the other hand, if the get parameter validation exception, they know it's their fault.

oefe
+1  A: 

An assertion reflects a state that should not ever occur and was not expected, where the application cannot continue executing for one reason or another, whereas an exception indicates a state that is not considered "normal", but that was not unexpected, and from which it might be possible to recover.

As an example, if I allocate space on the heap, and this allocation fails, then I can't continue working, so I assert that the address returned is valid; where it is invalid, the assertion fails, and the program fails with it.

On the other hand, if I open a file for reading, and it doesn't exist, then it might be possible to recover from the situation, in which case an exception is thrown (and caught, and handled as far as possible).

In general, assertions are most useful during the debugging phase, whereas exceptions are considered part of regular program flow and error handling. The general consensus is that assertions should be disabled in production code (to shield users from apparent crashes), whereas I have read a school of thought that argues this is counter-productive, and that the user should see the assertion failure, so that they can properly report the problem.

Personally, I sometimes combine the two techniques; usually, if I'm catching an exception that I do not believe could be thrown. Taking the example above, if I check the file's existence before attempting to open it, then I do not expect an exception to be thrown, and if one is, then I tend to deal with this by raising an assertion in the relevant catch block. I find this a particularly useful technique in Java, where such exceptions are fully checked.

Rob