例子:

def spam(div):
    return 42/div
print(spam(2))
print(spam(12))
print(spam(0)
print(spam(1)

运行以上程序则:

21.0
3.5
Traceback (most recent call last):
  File "\\localhost\D$\ 异常处理.py", line 5, in <module>
    print(spam(0))
  File "\\localhost\D$\ 异常处理.py", line 2, in spam
    return 42/div
ZeroDivisionError: division by zero

上面报错中出现的意思是0不能作为除数

例子修复1:

def spam(div):
    try:
        return 42/div
    except ZeroDivisionError:
        print("Error:Invalid argument.")

print(spam(2))
print(spam(12))
print(spam(0))
print(spam(1))

遇到问题继续往下执行,输出结果为:

21.0
3.5
Error:Invalid argument.
None
42.0

例子修复2:

def spam(div):
    return 42/div

try:
    print(spam(2))
    print(spam(12))
    print(spam(0))
    print(spam(16))
except ZeroDivisionError:
    print("Error:Invalid argument.")

遇到异常不往下执行,输出的结果为:

21.0
3.5
Error:Invalid argument.