Search code examples
exceptionassert

Why use assert instead of exception throwing?


In one of the online courses I am taking on Udacity regarding code debugging, the professor says it's better to use assert instead of exception throwing in the actual code.

Although through out my programming career I have never seen anyone use it.

Do you know why it is in fact? Do you agree?

PS: the below image is Python code, but I guess the idea applies to all programming languages. Also, this course is only 4 month old so I imagine the method taught is the most modern approach.

enter image description here


Solution

  • Assert is only for debugging, and allows you to check invariants in a one-liner. Asserts and similar macros are used ubiquitously in testing frameworks. With exceptions, you really need to care what the rest of your library or program is doing. Asserts are as simple as it gets.

    It will crash the program without any ambiguity as to what caused it - your assert caused it. It is easier to go there in a debugger. An exception may be caught and will not stop the program or may cause side-effects such as stack-unwinding from a place where it wouldn't normally occur, calling all the destructors, etc., when you don't really care about that since you're debugging.

    With exceptions, you need to declare functions to throw, must enable exceptions in languages like C++, etc.

    If you're debugging interactively and not just running test cases in batch mode, and as your example is in Python, I think you'd find a function that starts pdb and stops the program right there more helpful.