What is the difference between try/except and assert?

assert only check if a condition is true or not and throw an exception. A try/except block can run a few statements and check if any of them throw an exception so you can process it in the exceptpart. Examples:

assert(1 == 2)

will give you an AsertionError.

try:
    # some statements
    # ...
except OSError as err:
    #If an OSerror exception is thrown, you can process it here. For example:
    print("OS error: {0}".format(err))

Your code will look like this:

def function_addition(x,y):
    try:
        assert (y!=0)
    except:
        raise ValueError('y is 0.')
    total= x/y
    return total


num1=float(input("Write a number :"))
num2=float (input("Write a second number:"))
try:
    result=function_addition(num1,num2)
except ValueError as ve:
    print(ve)
else:
    print(result)

If you save it in a fun.py file and run it, you will have this output:

Write a number :1
Write a second number:2
0.5
# Run it again.
Write a number :0
Write a second number:0
y is 0.
原文地址:https://www.cnblogs.com/jfdwd/p/11086675.html