title: Error handling in R: tryCatch() syntax
body: <p>I am attempting to get my head around error handling in R. From reading the docs, I cannot find a clear definition of the correct syntax.</p>
  
  <p>Here is a self contained example:</p>
  
  <pre><code>foo &lt;- function(dat) {
      print('Calling foo()')
      print(dat[,'r1'])
      print(dat[,'r2'])
      print(dat[,'r3'])
      print('Finished foo()')
      return(dat$r3)
  }
  
  bar &lt;- function(dat) {
      print('Calling bar()')
      print(dat[,'r1'])
      print(dat[,'r2'])
      print('Finished bar()')
      return(dat$r2)
  }
  
  d1 &lt;- data.frame(r1 = 1:10, r2 = 11:20, r3 = 21:30)
  d2 &lt;- d1[c("r1", "r2")]
  
  print('Starting')
  print('trying d1')
  myVal1 &lt;- tryCatch(foo(d1), error = bar(d1))
  print('finished d1')
  print('trying d2')
  myVal2 &lt;- tryCatch(foo(d2), error = bar(d2))
  print('finished d2')
  print('Done')
  </code></pre>
  
  <p>Expected output:</p>
  
  <pre><code>[1] "Starting"
  [1] "trying d1"
  [1] "Calling foo()"
   [1]  1  2  3  4  5  6  7  8  9 10
   [1] 11 12 13 14 15 16 17 18 19 20
   [1] 21 22 23 24 25 26 27 28 29 30
  [1] "Finished foo()"
  [1] "finished d1"
  [1] "trying d2"
  [1] "Calling bar()"
   [1]  1  2  3  4  5  6  7  8  9 10
   [1] 11 12 13 14 15 16 17 18 19 20
  [1] "Finished bar()"
  [1] "finished d2"
  [1] "Done"
  </code></pre>
  
  <p>Actual output:</p>
  
  <pre><code>[1] "Starting"
  [1] "trying d1"
  [1] "Calling bar()"
   [1]  1  2  3  4  5  6  7  8  9 10
   [1] 11 12 13 14 15 16 17 18 19 20
  [1] "Finished bar()"
  [1] "Calling foo()"
   [1]  1  2  3  4  5  6  7  8  9 10
   [1] 11 12 13 14 15 16 17 18 19 20
   [1] 21 22 23 24 25 26 27 28 29 30
  [1] "Finished foo()"
  [1] "finished d1"
  [1] "trying d2"
  [1] "Calling bar()"
   [1]  1  2  3  4  5  6  7  8  9 10
   [1] 11 12 13 14 15 16 17 18 19 20
  [1] "Finished bar()"
  [1] "Calling foo()"
   [1]  1  2  3  4  5  6  7  8  9 10
   [1] 11 12 13 14 15 16 17 18 19 20
  Error in tryCatchOne(expr, names, parentenv, handlers[[1L]]) : 
    attempt to apply non-function
  </code></pre>
  
  <p>My questions:</p>
  
  <ol>
  <li><p>Why does this <code>tryCatch()</code> call end up running both functions?</p></li>
  <li><p>Why do I get the error reported above?</p></li>
  <li><p>Is my syntax of <code>tryCatch(someFunction(), error = someOtherFunction())</code> incorrect?</p></li>
  </ol>
  
  <p>Thanks!</p>