Created
May 29, 2015 20:35
-
-
Save trcook/19b5840529a645075279 to your computer and use it in GitHub Desktop.
Exit Statuses TryCatch in R
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#' Trycatch in R is setup in a really weird way. Usually you enter 3+ conditions as parameters (message, warning, error) and the function you would like run to handle the exception. | |
#" As such, you want to make use of the return command to return an exit status | |
#' The big caveat is that you want to use return to give exit statuses, but for the expression to be 'tried' itself, you can't use return (unless youwant to wrap the expression in a function, which is a pain. | |
#' To get an exit status, then you want to code the last part of the expression to return your exit status in the expression and the alternative exit statuses as return statements in the other parameters to trycatch | |
#' example: | |
exit_status<-tryCatch({ | |
x<-1 | |
y<-2 | |
m<-1 | |
0 | |
}, | |
warning=function(warn){print(warn) | |
return(1)}) | |
# returns an 'exit_staus' of 0, and defines x,y,m in the global environment | |
exit_status<-tryCatch({ | |
x<-1 | |
y<-2 | |
m<-1 | |
0 | |
}, | |
warning=function(warn){warning(warn) | |
return(1)}) | |
# defines x an y, gives error for m and yeilds exit status of 1 | |
exit_status<-tryCatch({ | |
x<-1 | |
y<-2 | |
m<-warning("oh noes") | |
0 | |
}, | |
warning=function(warn){warning(warn) | |
return(1)}) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment