Does anyone have examples/tutorials of exception handling in R? The official documentation is very terse.
+4
A:
Basically you want to use the tryCatch()
function. Look at help("tryCatch") for more details.
Here's a trivial example (keep in mind that you can do whatever you want with an error):
vari <- 1
tryCatch(print("passes"), error = function(e) print(vari), finally=print("finished"))
tryCatch(stop("fails"), error = function(e) print(vari), finally=print("finished"))
Have a look at these related questions:
- http://stackoverflow.com/questions/1608130/equivalent-of-throw-in-r
- http://stackoverflow.com/questions/2158780/r-catching-an-error-and-then-branching-logic
- http://stackoverflow.com/search?q=[r]+trycatch
Shane
2010-04-12 14:49:23
Third link is not a link.
Marek
2010-04-13 12:04:51
Not Shane's fault -- arguably a bug in the regexp determining how to mark up content on SO.
Dirk Eddelbuettel
2010-04-13 12:18:39
+5
A:
Besides Shane's answer pointing you to other StackOverflow discussions, you could try Google Code Search as e.g. in this query for tryCatch in language=R.
Just for the record, there is also try
but tryCatch
may be preferable. I tried a quick count at Google Code Search but try gets too many false positives for the verb itself -- yet it seems tryCatch
is more widely used.
Dirk Eddelbuettel
2010-04-12 15:52:28
no disrepect to Shane, but this way to look at examples is awesome. I suffered from a lack of examples. Very helpful.
gappy
2010-04-12 19:46:29
Yes, it rocks, and I banged my head hard when I was pointed to it not so long ago. And my most recent query was for ... tryCatch :)
Dirk Eddelbuettel
2010-04-12 19:50:13
I'd buy you a drink if you'd agreed to come to Chicago this week :)
Dirk Eddelbuettel
2010-04-12 21:04:12
Shane, if you come to Chicago you'll drink free all weekend. I guaran-damn-tee it. The offer is good for you too Gappy.
JD Long
2010-04-12 21:15:33