在Python中,使用def关键字定义函数时,可以使用try和except语句来处理函数内部的异常。以下是一个示例:
def divide(a, b):
try:
result = a / b
except ZeroDivisionError:
print("Error: Division by zero is not allowed.")
return None
except TypeError:
print("Error: Both inputs must be numbers.")
return None
else:
return result
# 测试函数
print(divide(6, 3)) # 输出:2.0
print(divide(6, 0)) # 输出:Error: Division by zero is not allowed.
print(divide(6, "a")) # 输出:Error: Both inputs must be numbers.
在这个示例中,我们定义了一个名为divide的函数,它接受两个参数a和b。在try块中,我们尝试执行除法操作。如果遇到ZeroDivisionError或TypeError异常,我们将在相应的except块中处理它们。如果没有异常发生,我们将在else块中返回结果。