R tryCatch 处理一种错误

R tryCatch handling one kind of error

我想知道这是检查 tryCatch 函数类型的错误或警告的方法,例如 Java。

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"

我们还可以使用 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$message 是否可以有多个字符串,在这种情况下,您可能还需要考虑使用 any 函数 if(any(e$message == "This error should be treated in some way"))