Defneit Defneit - 3 years ago 144
Python Question

Difference between Raise Try and Assert

So 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.

Answer Source

Assert is generally used by testing code to make sure that something worked:

def test_bool():
    assert True != False

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):

def validate_email(address):
    if not "@" in address:
        raise ValueError("Email Addresses must contain @ sign")

Then somewhere else in your code you can call the validate_email function and if it fails an exception will be thrown.

except ValueError as ex:
    print("We can do some special invalid input handling here, Like ask the user to retry the input")
    print("Finally always runs whether we succeed or not. Good for clean up like shutting things down.")

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:

if __name__ == '__main__':
    except Exception as ex:

Now you have no way of knowing why your application blew up.

One thing you will see often which is ok is something like:

import logging
if __name__ == '__main__':
    except Exception as ex:

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 server and then carry on with the next request, so in that case you don't want the program to end.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download