捕捉错误,然后分支逻辑 [英] catching an error and then branching logic

查看:122
本文介绍了捕捉错误,然后分支逻辑的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果发生错误,我如何编写R代码,让我在代码中执行不同的路径?我正在使用一个倾向于抛出错误的函数。当遇到错误条件时,我想执行一个不同的功能。以下是一个具体的例子:

How do I write R code that allows me to execute a different path in my code if an error condition happens? I'm using a function that tends to throw an error. When it meets an error condition I would like to execute a different function. Here's a specific example:

require(SuppDists)
parms <- structure(list(gamma = -0.841109044800762, delta = 0.768672140584442, 
    xi = -0.359199299528801, lambda = 0.522761187947026, type = "SB"), .Names = c("gamma", 
"delta", "xi", "lambda", "type"))
pJohnson(.18, parms)

pJohnson函数应该失败以下错误:

the pJohnson function should fail with the following error:

 Error in pJohnson(0.18, parms) :
 Sb values out of range.

我可以通过使用以下方式使错误无效:

I can make the error go silent by using:

try( pJohnson(.18, parms), silent=T)

但是我真正想做的是执行函数 alternativeFunction()如果 pJohnson(.18,parms)返回错误。

but what I really want to do is execute the function alternativeFunction() if pJohnson(.18, parms) returns an error.

看起来像C codeCallingHandlers()函数应该帮助我,但是我不知道如何捕获错误,使其仅在错误条件下运行 alternativeFunction()

It seems like the withCallingHandlers() function should help me out, but I can't figure out how to capture the error and make it run the alternativeFunction() only upon an error condition.

推荐答案

t <- try(pJohnson(.18, parms))
if("try-error" %in% class(t)) alternativeFunction()

这篇关于捕捉错误,然后分支逻辑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆