For R v1.8.0 you can use tryCatch() (it's great) to catch objects of
class 'condition' and just print() them (instead of letting them
generate errors) like this:

for(i in 1:3) {
  file <- paste("file", i, ".dat", sep="")
  tryCatch({
    bb <- read.table(file)
    x11()
    plot(bb)
    dev.off()
  }, condition=function(ex) {
    print(ex);
  })
}

As soon as/if an error is generated, tryCatch() will catch it an call
the condition function, which will print it.

Details:
If the file does not exists when calling read.table() both a warning
and an error is generated. Since warnings are now of class
simpleWarning and (stop) errors are of class simpleError and both
these are subclasses (via the abstract classes 'warning' and 'error',
respectively) of class 'condition', which is the root class of all
exception classes, it is best to catch by using 'condition' above. If
one use 'error=...' instead, warnings will still be shown.

Moreover, a shorter version of the above would be to use
'condition=print'.
 

Some further comments:
 1) Your code is not correct, e.g. "[1:3]".
    Please submit example code that is executable!
 2) Did you forget sep="" in the paste line?
 1) avoid using "=" to assign; or at least be consistent.

Cheers

Henrik Bengtsson

> -----Original Message-----
> From: [EMAIL PROTECTED] 
> [mailto:[EMAIL PROTECTED] On Behalf Of Susan Lin
> Sent: den 9 mars 2004 18:12
> To: [EMAIL PROTECTED]
> Subject: [R] how to use conditional statements to handle exceptions?
> 
> 
> Hello,
> 
> I have a problem to handle the following statements.
>   
>   for(i in [1:3])
>   {
>     file=paste("file", i, ".dat")
>     bb <- read.table(file)
>     x11()
>     plot(bb)
>     dev.off()
> 
>   }
> When the input .dat file is empty, the program stops
> running and an error message appears. Could someone
> tell me how to handle this exception?
> 
> Thanks
> 
> ______________________________________________
> [EMAIL PROTECTED] mailing list 
> https://www.stat.math.ethz.ch/mailma> n/listinfo/r-help
> PLEASE 
> do read the posting guide! 
> http://www.R-project.org/posting-guide.html
> 
>

______________________________________________
[EMAIL PROTECTED] mailing list
https://www.stat.math.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html

Reply via email to