Are there any significant differences with the following?
raise Exception("some exception")
assert False, "some exception"
raise is used for raising an exception; assert is used for raising an exception if the given condition is False .
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With