我刚刚开始我的 python 学习之旅,需要一些帮助以正确的方式引发异常。
考虑一个循环遍历列表并执行任务的代码块。如果发生异常,则继续执行程序。并执行其余代码。在程序结束时引发异常并使用非零代码系统化应用程序。这个想法是程序应该继续执行所有任务,但退出时使用非 0 代码供外部应用程序跟踪和报告。
save_exc_info = None
def numMatcher(numbers):
try:
if numbers != 2:
print('number match ' + str(numbers))
else:
raise ValueError('Number not in list. Will be logged for troubleshooting') # raise exception and log it
except ValueError as veer: # exception 1 caught and saved
save_exc_info = sys.exc_info()
except (IOError, OSError) as ioerr: # exception 2 caught and saved
save_exc_info = sys.exc_info()
try:
print('Next step') # Perform rest of the tasks in the code
except Exception as excp: # exception 3 caught and saved
save_exc_info = sys.exc_info()
print('final step')
numlist = [1, 2, 3]
for numbers in numlist:
numMatcher(numbers)
if save_exc_info is not None:
traceback.print_exception(*save_exc_info) # how to return the right exception and print?
sys.exit(1) # At the end of the program, exit with non zero code as there was an exception in the program.
喵喵时光机
一只甜甜圈
随时随地看视频慕课网APP
相关分类