Friday, September 03, 2010

Asserts, Exceptions

This is rather random, but I need to save the search results.


This is a discussion of when to use asserts and when to use exceptions.

Asserts only exist in debug.

Asserts terminate normal program execution.

Rule of thumb: 

Can the error be managed?
Yes - throw exception and handle it.
No - use assert.

Can you write a unit test that is able to throw the exception?
Yes - exception
No - assert

Are you protecting against a coding error?
Yes - assert
No - exception

Are you protecting against 'normal program' (i.e. file not writable etc.):
Yes - exception
No - assert

Exception example:


http://msdn.microsoft.com/en-us/library/ac9f67ah.aspx

 try {    throw CSomeOtherException(); } catch(...) {  // Handle all exceptions    // Respond (perhaps only partially) to exception    throw;       // Pass exception to some other handler }



No comments: