December 30, 2013

Simple try-catch code in R

Here is a simple code sample to demonstrate tryCatch function in R.


x <- tryCatch( "OK", 
          warning=function(w){     
            return(paste( "Warning:", conditionMessage(w)));
          }, 
          error = function(e) {      
            return(paste( "Error:", conditionMessage(e)));
          }, 
          finally={
            print("This is try-catch test. check the output.")
          });
print(x);

x <- tryCatch( warning("got a warning!"), 
               warning=function(w){     
                 return(paste( "Warning:", conditionMessage(w)));
               }, 
               error = function(e) {      
                 return(paste( "Error:", conditionMessage(e)));
               }, 
               finally={
                 print("This is try-catch test. check the output.")
               });
print(x);


x <- tryCatch( stop("an error occured!"), 
               warning=function(w){     
                 return(paste( "Warning:", conditionMessage(w)));
               }, 
               error = function(e) {      
                 return(paste( "Error:", conditionMessage(e)));
               }, 
               finally={
                 print("This is try-catch test. check the output.")
               });
print(x); 

1 comment:

  1. Great examples. Thanks heaps. I found them very accessible and useful.

    ReplyDelete