R tryCatch handling one kind of error
Asked Answered
E

2

3

I wondering it is the way to check in tryCatch function kind of errors or warnings like in Java for example.

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;
        }

In R I only find solution for handling all error in one ways, example

result = tryCatch({
    expr
}, warning = function(w) {
    warning-handler-code
}, error = function(e) {
    error-handler-code
}, finally = {
    cleanup-code
}
Explant answered 9/11, 2017 at 9:28 Comment(1)
I've added another way of handling errors using tryCatch and I've noticed that a closing parenthesis is missing in the end of your second example. (I cannot edit your post to change only one character, so I leave it as a comment. This comment can be deleted afterwards.)Plainsman
U
3

You could use try to handle errors:

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"
Urbanist answered 9/11, 2017 at 9:37 Comment(1)
Glad to help, feel free to accept my answer as your final solutionUrbanist
P
1

We can also handle errors using tryCatch and analysing the message that comes out, in your example it would be e$message. I've adapted your example to this case.

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
}
)

(I'm not sure if e$message can have more than one string, in that case, you may want to consider also using the any function if(any(e$message == "This error should be treated in some way"))

Plainsman answered 17/2, 2021 at 12:28 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.