Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the implications of using assert vs. raise Exception

Tags:

python

Are there any significant differences with the following?

raise Exception("some exception")

assert False, "some exception"
like image 811
cammil Avatar asked Nov 19 '13 15:11

cammil


People also ask

What is the use of raise and assert in exception handling?

raise is used for raising an exception; assert is used for raising an exception if the given condition is False .

When to use raise or assert?

raise is typically used when you have detected an error condition or some condition does not satisfy. assert is similar but the exception is only raised if a condition is met. raise and assert have a different philosophy. There are many "normal" errors in code that you detect and raise errors.

What is the difference between assert and exception?

The key differences between exceptions and assertions are: Assertions are intended to be used solely as a means of detecting programming errors, aka bugs. By contrast, an exception can indicate other kinds of error or "exceptional" condition; e.g. invalid user input, missing files, heap full and so on.


1 Answers

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.

like image 151
svk Avatar answered Sep 23 '22 23:09

svk