I have been learning Python for a while and the raise
function and assert
are (what I realised is that both of them crash the app, unlike try - except) really similar and I can't see a situation where you would use raise
or assert
over try
.
So, what is the difference between Raise, Try and Assert?
Assertions
syntax:
assert_stmt ::= "assert" expression1 ["," expression2]
at execution time it translates to:
__debug__
is a built-in flag that is usually true, but if optimisations are triggered it will be false, thus assertions will be dead code => disabled with the -O and -OO flags when starting Python (or PYTHONOPTIMIZE env variable in CPython), so, don't rely on them for code logic.assert (<some_test>, 'warn string')
=> notice the tuple construct (wrong!)Check: Catching bogus Python asserts on CI by Dan Bader
Raise/Exceptions
Try
BTW, I highly recommend the book, "Python Tricks: The Book" by Dan Bader (from realpython.com)
Assert is generally used by testing code to make sure that something worked:
Where as try, raise and except makeup exception handling which is the preferred way in python to handle and propagate errors.
Most libraries and the python built-ins will raise and Exception of one type or another if something goes wrong. Often in you own code you will also want to raise an exception when you detect something going wrong. Let's say as an example you were writing an email address validator and you wanted to raise an exception if the address didn't contain an @ sign. you could have something like (This is toy code, don't actually validate emails like this):
Then somewhere else in your code you can call the validate_email function and if it fails an exception will be thrown.
The important thing to know is that when an exception is raised it gets passed up the call stack until it finds a handler. If it never finds a handler then it will crash the program with the exception and the stack trace.
One thing you don't want to do is something like:
Now you have no way of knowing why your application blew up.
One thing you will see often which is ok is something like:
The raise in this case since it has no parameters re-raises the same error. Often in web code you will see something similar that does not re-raise the exception because it will send the 500 error to the client and then carry on with the next request, so in that case you don't want the program to end.
Exceptions are what Python (and some other languages) use to deal with errors that arise when executing code.
raise ExceptionName
is saying that there is an error in the code, and specifies what kind of problem it is by raising the Exception associated with that problem.assert expression
evaluateexpression
and raises an Exception if it is false.try
is used to execute code that might raise an Exception that you're expecting. Instead of stopping the program, you can "catch" the exception and deal with it in your code.Example: Let's say that you have a dictionary and a list. You want to look things from the list in the dictionary until you reach one that isn't in the dictionary:
try/except
blocks let you catch and manage exceptions. Exceptions can be triggered byraise
,assert
, and a large number of errors such as trying to index an empty list.raise
is typically used when you have detected an error condition.assert
is similar but the exception is only raised if a condition is met.raise
andassert
have a different philosophy. There are many "normal" errors in code that you detect and raise errors on. Perhaps a web site doesn't exist or a parameter value is out of range.Assertions are generally reserved for "I swear this cannot happen" issues that seem to happen anyway. Its more like runtime debugging than normal runtime error detection. Assertions can be disabled if you use the
-O
flag or run from.pyo
files instead of.pyc
files, so they should not be part of regular error detection.If production quality code raises an exception, then figure out what you did wrong. If it raises an
AssertionError
, you've got a bigger problem.is expanded to something like
use assert because it is more readable.
raise
- raise an exception.assert
- raise an exception if a given condition is (or isn't) true.try
- execute some code that might raise an exception, and if so, catch it.