我正在使用 R 中的 stop
函数来采取一些故障排除措施。例如,当数据输入错误时抛出错误。我想要一个可以调用的通用函数来执行此检查,然后可以在父代码的几个不同点中调用该函数。我可以很好地抛出错误,但是,我注意到父函数在抛出错误后继续执行,并且只有我的“错误函数”(如果您停止执行)。当 stop
发生错误时,有没有办法让 R 停止全局执行?
谢谢。
我的问题的编码示例:
StopCode <- function() {
try(if(TRUE) stop("This try/if statement should stop the code from executing."))
}
StopCode() # This function should stop the code!
print("I should not see this statement if the try/if statement stopped the code in the way I desired.")
控制台:
Error in try(if (TRUE) stop("This try/if statement should stop the code from executing.")) :
This try/if statement should stop the code from executing.
[1] "I should not see this statement if the try/if statement stopped the code in the way I desired."
期望的结果应该是 StopCode 函数完全停止代码,而不仅仅是函数的执行。当您获取此代码时,它会停止该函数,发出警告,然后继续运行打印函数。我希望这种情况不会发生,并且函数中的停止会全局终止执行。
最佳答案
默认情况下,stop
完全按照您希望的方式执行:它会中断每个正在运行的函数,直到到达顶层 - 并且,如果脚本以非交互方式运行,它会中断然后停止脚本。
但是,在您发布的代码中,您通过 try
捕获错误,明确告诉 R 不要停止执行调用函数。目前还不清楚为什么在这里使用 try
,因为它的唯一目的是阻止您似乎想要的行为。
解决方案只是从代码中删除 try
。或者,您可能想要捕获错误,处理它,然后重新抛出它:
result = try(‹some operation that may fail›)
if (inherits(result, 'try-error')) {
‹handle error›
# Re-throw error:
stop(attr(result, 'condition'))
}
关于r - 在 R 中停止子函数执行父函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32358116/