Reputation: 11
I am new to Python and would like to know what is the difference between Try and assert and situations where each one is more suitable. Thanks.
Upvotes: 0
Views: 94
Reputation:
Welcome to Stack Overflow.
You can read the documentation for try
here: https://docs.python.org/3/tutorial/errors.html
You can read the documentation for assert
here:
https://docs.python.org/3/reference/simple_stmts.html
Essentially, try
means try the following block of code, and if there is an error, it is handled in the except
part.
For example:
try:
print(1/0) #a division by 0, should raise an error.
except ZeroDivisionError:
print("You tried to divide by zero!")
So instead of the program crashing, it prints "you tried to divide by zero" instead.
assert
means "make sure the following is true".
So imagine if we had a function that did division, and we wanted to make sure that the denominator was never zero, we could do:
def divide(a, b):
assert b != 0
return a/b
This is a pretty bad example, but basically what's happening here is that if b is ever equal to 0, the assertion raises an exception, which prevents the program from continuing unless that exception is handled.
Upvotes: 1