0

I want to make a message in my function that tells the user to pass in the argument as a string, that is if they forget the quotation marks then the message should say "use quotation marks" and not "object X not found". Is that possible?

print_name <- function(name){
  if (!is.character(name)){
    stop("Name should be a character")
  }
  else {
    print(name)
  }
}

print_name(david)
#> Error in print_name(david): object 'david' not found

print_name("david")
#> [1] "david"

Created on 2019-05-24 by the reprex package (v0.2.1)

1 Answer 1

4

We can use tryCatch

print_name <- function(name){
   tryCatch({
     if (is.character(name))
       print(name)
     else
       print("not a character")
    }, error = function(e) {
    stop("Name should be a character - use quotes!")
  })
}

and then run the function

print_name(david)

Error in value[3L] : Name should be a character - use quotes!

print_name("david")
#[1] "david"

print_name(2)
#[1] "not a character"
Sign up to request clarification or add additional context in comments.

1 Comment

@David It's a variable to catch the error message. If you print e$message in the error function you will get the actual error message (in this case object 'david' not found) so that you can take actions based on that if required.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.