R tryCatch处理一种错误
我想知道这是一种签入tryCatch函数的方法,比如Java中的错误或警告R tryCatch处理一种错误,r,error-handling,try-catch,suppress-warnings,error-suppression,R,Error Handling,Try Catch,Suppress Warnings,Error Suppression,我想知道这是一种签入tryCatch函数的方法,比如Java中的错误或警告 try { driver.findElement(By.xpath(locator)).click(); result= true; } catch (Exception e) { if(e.getMessage().contains("is not clickable at point")) {
try {
driver.findElement(By.xpath(locator)).click();
result= true;
} catch (Exception e) {
if(e.getMessage().contains("is not clickable at point")) {
System.out.println(driver.findElement(By.xpath(locator)).getAttribute("name")+" are not clicable");
} else {
System.err.println(e.getMessage());
}
} finally {
break;
}
在R中,我只找到用一种方法处理所有错误的解决方案,例如
result = tryCatch({
expr
}, warning = function(w) {
warning-handler-code
}, error = function(e) {
error-handler-code
}, finally = {
cleanup-code
}
您可以使用
try
来处理错误:
result <- try(log("a"))
if(class(result) == "try-error"){
error_type <- attr(result,"condition")
print(class(error_type))
print(error_type$message)
if(error_type$message == "non-numeric argument to mathematical function"){
print("Do stuff")
}else{
print("Do other stuff")
}
}
# [1] "simpleError" "error" "condition"
# [1] "non-numeric argument to mathematical function"
# [1] "Do stuff"
result我们还可以使用tryCatch处理错误并分析产生的消息,在您的示例中是e$message
。我把你的例子改编成这个例子
result = tryCatch({
expr
}, warning = function(w) {
warning-handler-code
}, error = function(e) {
if(e$message == "This error should be treated in some way"){
error-handler-code-for-one-type-of-error-message
}
else{
error-handler-code-for-other-errors
}
}, finally = {
cleanup-code
}
)
(我不确定E$消息是否可以有不止一个字符串,在这种情况下,您可能需要考虑使用<代码>任何< /Cult>函数<代码>(如果(E$消息==)这个错误应该以某种方式处理))
很高兴为您提供帮助,请随意接受我的答案作为您的最终解决方案。我使用tryCatch
添加了另一种处理错误的方法,我注意到您的第二个示例末尾缺少一个右括号。(我无法编辑您的帖子以仅更改一个字符,因此我将其保留为评论。此评论可以在以后删除。)