s-news
[Top] [All Lists]

Any way to trap errors in a For() loop - try() seems to have a bug ?

To: <s-news@lists.biostat.wustl.edu>
Subject: Any way to trap errors in a For() loop - try() seems to have a bug ?
From: "Malcolm Hawkes" <mhawkes@xcaliber.com>
Date: Thu, 30 Jan 2003 12:19:26 -0600
Thread-index: AcLIjTJyYGqSpym+QNecSRvpJBnIwA==
Thread-topic: Any way to trap errors in a For() loop - try() seems to have a bug ?
I'm using the For() function to scan() in hundreds of very large text files - 
if I use for() instead I run out of memory.
Occasionally the text files will be corrupted and and scan() will generate an 
error, what I'd like to do is trap the error and
load the next text file, however, the whole process halts and no more files are 
loaded.  I tried wrapping the call to the loading process within try however I 
found that it only works inside a for() loop not a For() loop.  This seems to 
be a bug in the try() function as the following example shows:

Create the function

errCatchTest <- function(n)
{
  cat(paste("n=",n,"\n", sep=""), file="try_test.txt",  append=T)
  if ( n == 7 )
    pront("Error") ## Causes an error
}
        
Then try

> cat("little for\n", file="try_test.txt",  append=T)
> for (n in 1:10){
>       try(errCatchTest(n))
> }

which produces

Problem in errCatchTest(n): Couldn't find a function definition for "pront" 
Use traceback() to see the call stack

on the screen and then try

> cat("BIG FOR\n", file="try_test.txt",  append=T)
> For(n=1:10,try(errCatchTest(n)),grain.size=1)

which produces screen output

Warning in For(n = 1:10, try(errCatchTest(n)), grai..: Errors ocurred in 
subprocess --
results are wrong or incomplete

After doing this the contents of the file try_test.txt is

little for
n=1
n=2
n=3
n=4
n=5
n=6
n=7
n=8
n=9
n=10
BIG FOR
n=1
n=2
n=3
n=4
n=5
n=6
n=7

so the for() function continued with the next iterations of the loop after the 
error was generated but For() didn't.
Is there any way to make the For() function exhibit the same behaviour as the 
for() function with regards to handling the trapped error ??

Thanks

Malcolm


System info: S+ version 6.1 for windows release 1 running under Windows 2000 
Server


Malcolm Hawkes
Research Associate
Ronin Capital LLC
230 S. LaSalle, 4th Floor
Chicago, IL 60604
Voice: 312-244-5765
Fax: 312-244-5837


<Prev in Thread] Current Thread [Next in Thread>
  • Any way to trap errors in a For() loop - try() seems to have a bug ?, Malcolm Hawkes <=