Just Emil Kirkegaard Things

Share this post

Error handling in R is odd

www.emilkirkegaard.com

Discover more from Just Emil Kirkegaard Things

No filter science
Over 5,000 subscribers
Continue reading
Sign in

Error handling in R is odd

Emil O. W. Kirkegaard
Apr 27, 2015
Share this post

Error handling in R is odd

www.emilkirkegaard.com
Share

So you want to run some code that may throw an error? This is somewhat less common with R than with e.g. php.

It is quite simple in Python:

The try statement works as follows.

  • First, the try clause (the statement(s) between the try and except keywords) is executed.

  • If no exception occurs, the except clause is skipped and execution of the try statement is finished.

  • If an exception occurs during execution of the try clause, the rest of the clause is skipped. Then if its type matches the exception named after the except keyword, the except clause is executed, and then execution continues after the try statement.

  • If an exception occurs which does not match the exception named in the except clause, it is passed on to outer try statements; if no handler is found, it is an unhandled exception and execution stops with a message as shown above.

Let's try something simple in iPython:

In [2]: try:
   ...:     "string"/7
   ...: except:
   ...:     print("Can't divide a string")
   ...:
Can't divide a string

Simple stuff.

Now, let's do the same in R:

tryCatch("string"/7,
         error = function(e) {
           print("Can't divide a string")
         }
)

Notice how I had to add an anonymous function? Well apparently this is how it has to be done in R. The parameter to the function, e, is not even used. It would be better if one could simply do this:

tryCatch("string"/7,
         error = {
           print("Can't divide a string")
         }
)

But no, then you get:

[1] "Can't divide a string"
Error in tryCatchOne(expr, names, parentenv, handlers[[1L]]) : 
  attempt to apply non-function
Share this post

Error handling in R is odd

www.emilkirkegaard.com
Share
Comments
Top
New
Community

No posts

Ready for more?

© 2023 Emil O. W. Kirkegaard
Privacy ∙ Terms ∙ Collection notice
Start WritingGet the app
Substack is the home for great writing