An assertion is usually used when testing code to make sure something works:
def test_bool(): assert True != False
Where as a try, raise and exclude makeup exception handling, which is the preferred way in python to handle and propagate errors.
Most libraries and python built-in modules will go up and throw an exception of one type or another if something goes wrong. Often in your own code, you also want to throw an exception if you find that something is wrong. Say, as an example, you are writing an email address validator, and you wanted to throw an exception if the address did not contain the @ sign. you might have something like this (this is a toy code, don't really check for such emails):
def validate_email(address): if not "@" in address: raise ValueError("Email Addresses must contain @ sign")
Then, in another place in your code, you can call the validate_email function, and if it finishes, an exception will be thrown.
try: validate_email("Mynameisjoe.com") except ValueError as ex: print("We can do some special invalid input handling here, Like ask the user to retry the input") finally: close_my_connection() print("Finally always runs whether we succeed or not. Good for clean up like shutting things down.")
It is important to know that when an exception occurs, it skips the call stack until it finds a handler. If he never finds a handler, he will abort the program with an exception and a stack trace.
One thing you don't want to do is something like:
if __name__ == '__main__': try: print(1/0) except Exception as ex: pass
Now you have no way to find out why your application exploded.
One thing you'll often see, and this is normal:
import logging if __name__ == '__main__': try: print(1/0) except Exception as ex: logging.exception(ex) raise
Raising in this case, since it has no parameters, repeatedly causes the same error. Often in the web code you will see something similar that does not restore the exception, because it will send an error to the client 500 and then continue the next request, so in this case you do not want the program to end.