Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to use assert() and when to use try catch?

Tags:

In which situations do you use them?

like image 302
Demian Kasier Avatar asked Dec 02 '10 09:12

Demian Kasier


2 Answers

Try... catch - for exceptional conditions, i.e. conditions which aren't caused by malformed code, but which may just alter the normal control flow by external unpredictable events.

Assertions for catching invalid code, i.e. checking if an invariant is held in the function, checking if an internal method is called with right arguments (for public API you might still want an exception for that), etc.

Those are my basic guidelines, but the conventions vary from situation to situation and from language to language.


When you're in doubt, you can ask yourself: is that specific safety check supposed to still be there in the release code, after we test and finish everything? If you answer "yes, it's still neccessary then", you probably want an exception. Otherwise, you probably want an assertion.

like image 166
Kos Avatar answered Oct 15 '22 22:10

Kos


Normally assert() does not work in release code, so it can never replace a try-catch strategy. Nevertheless I like to use assert() in places where exceptions are thrown. For me (as a developer!), it is often more convenient to get by an assert() message to the line of failure than through the exception stack.

like image 26
tanascius Avatar answered Oct 15 '22 21:10

tanascius