From emil@bode @ending from d@n@@kn@w@nl  Fri Nov 23 13:17:06 2018
From: emil@bode @ending from d@n@@kn@w@nl (Emil Bode)
Date: Fri, 23 Nov 2018 12:17:06 +0000
Subject: [Rd] [tryExcept] New try Function
In-Reply-To: <ADFC5C3F-9849-4AF3-86B0-017615152298@gmail.com>
References: <ADFC5C3F-9849-4AF3-86B0-017615152298@gmail.com>
Message-ID: <97C3B2B2-A8C8-4A6B-B609-1964F16A4A1C@dans.knaw.nl>

Hi Ernest,

To start: I don't see an attachment, I think they're not (always) allowed on this mailing-list. If you want to send something, text is your safest bet.
But regarding the issue of tryCatch: I think you're not fully using what it already can do. In almost all circumstances I've encountered the following works fine:
res <- tryCatch(expr, error = function(cond) {
  # a bunch of code
  # Some value to be stored in res
})
The only difference is that now "#abunchofcode" is run from inside a function, which means you're working in a different environment, and if you want to assign values to other variables you need to use <<- or assign.
For a modified function, I think it would be nice if there's a way to supply an expression instead of a function, so that evaluation (and assignment!) takes place in the same environment as the main code in the tryCatch (in expr). Is that what you made?
And with the current tryCatch, you could use something like this:
res <- tryCatch(expr, error=function(e) evalq({
  # a bunch of code
  # Some value for res
}, envir=parent.frame(4))) # The 4 is because some internal functions are involved, parent.frame(4) is the same environment as used by expr

Although this is cumbersome, and it gets even more cumbersome if you want to access the error-object in #abunchofcode, or use #abunchofcode to return to a higher level, so I get it you're looking for a more elegant solution.

Best regards, 
Emil Bode
 
?On 23/11/2018, 08:49, "R-devel on behalf of Ernest Benedito" <r-devel-bounces at r-project.org on behalf of ebeneditos at gmail.com> wrote:

    Hi everyone,
    
    When dealing with errors, sometimes I want to run a bunch of code when an error occurs.
    For now I usually use a structure such as:
    
    res <- tryCatch(expr, error = function(cond) cond) # or try(expr)
    
    if (inherits(res, ?error?)) # or inherits(res, ?try-error?)
      # a bunch of code
    
    I though it would be useful to have a function that does this naturally, so I came up with the attached function.
    
    I would be glad to hear your insights and if you think it would make sense to add this function to R.
    
    Best regards,
    Ernest
    ______________________________________________
    R-devel at r-project.org mailing list
    https://stat.ethz.ch/mailman/listinfo/r-devel
    


[Rd] [tryExcept] New try Function
Emil Bode