代码之家  ›  专栏  ›  技术社区  ›  Bartosz Gurgul

R tryCatch处理一种错误

  •  3
  • Bartosz Gurgul  · 技术社区  · 8 年前

    我想知道这是一种签入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
    }
    
    2 回复  |  直到 8 年前
        1
  •  3
  •   tobiasegli_te    8 年前

    你可以用 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"
    
        2
  •  0
  •   Ertxiem - reinstate Monica    5 年前

    我们还可以使用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"))