'TryCatch exception handling in R

I have a function which take input and return as per the logic , I am new to trycatch and not able to get the respective results which I want, I would appreciate if someone could help

  1. if the library SHAPforxgboost is not present , I want to stop the function and return an exception which states please install the library

  2. I have to check the input of the function , if it's not dataframe or matrix stop the function and return an exception/ error stating that wrong input please enter data frame or matrix as input only.

Also if possible is there any better way to check the input , it seems like a clumsy way of checking if dataframe or matrix present or not as per my logic

example<-function(a){
  
  library("SHAPforxgboost")    ### Throw an custom error that library is not present please install                            
                               ### the  library and stop the function and return the error as o/p
   
                              ### Similarly if the input is not dataframe or matrix, stop the function 
                              ### and return custom error wrong input
  if("data.frame"==class(a)){
      print("correct input")
  }else if("matrix"==class(a)){
    print("correct input")
  } else{print("wrong input")}  
  return(x)
}
e<-as.vector(3)
s<-as.data.frame(4)
p<-as.matrix(2)
example(e)
example(s)
example(p)




Solution 1:[1]

You can check for condition and stop the execution if the condition is not satisfied.

example<-function(a){

  if(!'SHAPforxgboost' %in% rownames(installed.packages()))
    stop('Please install SHAPforxgboost library')
  if(!(is.data.frame(a) | is.matrix(a)))
    stop('data should be either dataframe or matrix')
  #Do something
  #Do something
  #Return something
  return(x)
}

Solution 2:[2]

I hope this simple example helps:

divide = function(a,b)
      if(a/b)
        a/b

tryCatch({divide(10,'k')},
         error = function(e)
           {
           print("error in division")
         },
         finally = {
           print("in finally")
         })

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Ronak Shah
Solution 2 urvi jain