下面就是在Python中使用try catch的示例,一个标准的语法
# Python try and except method
try:
number = 24/0
# execute except block if zero division occur
except ZeroDivisionError:
print("Cannot divide by zero")
# Always run finally block
finally:
print("This block successfully was executed!")
输出:
Cannot divide by zero
This block successfully was executed!
当然你也可以同时捕获多种类型的Excption
# Python try and except method
try:
import math
number = 24/6
print(number)
# run except block if module error occur
except ModuleNotFoundError:
print("No module exist")
# run except blcok if zero division occurs
except ZeroDivisionError:
print("Cannot divide by zero!")
# Always run finally block
finally:
print("Good job!")
输出:
4.0
Good job!
当然我们还可以定义错误预言如下:
try:
denominator = 0
assert denominator != 0, "Cannot divide by zero"
print(24/ denominator)
# executes the assertionError if assert condition is false
except AssertionError as msg:
print(msg)
输出:
Cannot divide by zero
如果你还是在使用python2刚上面这种方式暂时还不被 支持。
lebang2020.cn