cammil
cammil

Reputation: 9899

What are the implications of using assert vs. raise Exception

Are there any significant differences with the following?

raise Exception("some exception")

assert False, "some exception"

Upvotes: 18

Views: 7814

Answers (2)

Dirk Herrmann
Dirk Herrmann

Reputation: 5939

To extend a bit on @svk's answer (which already describes the technical differences and shortly addresses the conceptual difference): Assertions and exceptions are meant to be used for different purposes.

You can think of an assertion as a construct that is meant to provide information to developers. That is, if properly used, an assertion will inform a reader of the code (or, a static checker) about a condition that has to be fulfilled at run-time for the code to be correct. Similarly, an assertion that fails at run-time will convey the information that somewhere in the code there is a bug that needs fixing. Since the detection of a bug means that the software is unreliable (there is no way to predict what will happen if you continue), and since there is no way for the software itself to handle it (the code can't fix itself), it is often wise to just terminate the execution - and that is why you should not catch the AssertionError and continue.

In contrast, an exception would normally not be used to identify the presence of bugs in the software, but to identify exceptional situations for which there is likely some way of handling them on a higher level (where the exception is caught).

Upvotes: 2

svk
svk

Reputation: 5919

Assertions can be disabled with the -O flag when starting Python. For this reason, use assertions only for sanity-checking, not for checking that is part of your program logic.

Besides this, there is of course the difference that assertions raise AssertionError, which you really shouldn't catch. When you raise an exception, you can make the type of the exception appropriate to the error and catch it later.

Upvotes: 38

Related Questions