[英]Python fuction does not terminate after exception handling
如果我可以问:
即使在异常处理例程之后,我的 python 代码也不会终止。
这是代码:
import numpy as np
def calculate(num_list):
try:
num_array = np.array(num_list)
num_array = np.reshape(num_array, (3, 3))
# If the number of elements in num_list
# is less than 9, np.reshape will return a
# ValueError
except ValueError:
print("List must contain nine numbers.")
# The problem is that after catching error with
# except ValueError:, the function continues
# and runs the three lines below.
# And so, since num_array is not a valid input, I get
# an axis value error.
mean_list.append(np.mean(num_array, axis=0).tolist())
mean_list.append(np.mean(num_array, axis=1).tolist())
mean_list.append(np.mean(num_array).tolist())
我已经能够通过使用解决这个问题:
sys.stop() # After the print statement #
或者在 mean_list.append 代码之前添加一个 if 语句
if len(np.array(num_list)) >= 9:
但是,我确定我的异常处理有问题。 如果有人能解释我遗漏了什么,将不胜感激。
非常感谢。 欣赏它。
您只捕获异常以记录一些信息,但希望异常传播回调用者。 所以只需再加注。
import numpy as np
def calculate(num_list):
try:
num_array = np.array(num_list)
num_array = np.reshape(num_array, (3, 3))
# If the number of elements in num_list
# is less than 9, np.reshape will return a
# ValueError
except ValueError:
print("List must contain nine numbers.")
raise
# or return an error (and return True otherwise)
# return False
# or convert to a different exception
# raise MyAppError("Calculation Failed")
# or just change the message (and probably not print anything)
# raise ValueError("List must contain nine numbers.")
# or fix the problem
# num_array = my_default_array
mean_list.append(np.mean(num_array, axis=0).tolist())
mean_list.append(np.mean(num_array, axis=1).tolist())
mean_list.append(np.mean(num_array).tolist())
捕获异常后,您有多种选择。 也许问题可以解决,程序可以继续。 也许您想将异常转换为另一种异常类型。 也许您想将该异常转换为错误返回值。 默认情况下,python 假定您只想在 try/except 块的末尾继续执行。
except
块被编译except
您可以使用return
退出函数
import numpy as np
def calculate(num_list):
try:
num_array = np.array(num_list)
num_array = np.reshape(num_array, (3, 3))
# If the number of elements in num_list
# is less than 9, np.reshape will return a
# ValueError
except ValueError:
print("List must contain nine numbers.")
return
# The problem is that after catching error with
# except ValueError:, the function continues
# and runs the three lines below.
# And so, since num_array is not a valid input, I get
# an axis value error.
mean_list.append(np.mean(num_array, axis=0).tolist())
mean_list.append(np.mean(num_array, axis=1).tolist())
mean_list.append(np.mean(num_array).tolist())
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.