-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathtryCatch_template.R
56 lines (52 loc) · 2.11 KB
/
tryCatch_template.R
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# Simple Template
myfunction <- function(argument1) {
out <- tryCatch({insert_expression_here},
error = function(cond){
print("custom error message")
return(NA)
},
warning = function(cond){
print("custom warning message")
return(NA)
},
finally = {})
}
# More complicated template (example w/ reading a url using readlines)
# Code source: http://stackoverflow.com/questions/12193779/how-to-write-trycatch-in-r
readUrl <- function(url) {
out <- tryCatch(
{
# Just to highlight: if you want to use more than one
# R expression in the "try" part then you'll have to
# use curly brackets.
# 'tryCatch()' will return the last evaluated expression
# in case the "try" part was completed successfully
message("This is the 'try' part")
},
error=function(cond) {
message("___ caused an error")
message("Here's the original error message:")
message(cond)
# Choose a return value in case of error
return(NA)
},
warning=function(cond) {
message("___ caused a warning")
message("Here's the original warning message:")
message(cond)
# Choose a return value in case of warning
return(NULL)
},
finally={
# NOTE:
# Here goes everything that should be executed at the end,
# regardless of success or error.
# If you want more than one expression to be executed, then you
# need to wrap them in curly brackets ({...}); otherwise you could
# just have written 'finally=<expression>'
message("[Insert action taken]")
message("Some other message at the end")
}
)
return(out)
}