Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
809 views
in Technique[技术] by (71.8m points)

error handling - Functions and try() in R

Still struggling with R, especially with error handling:

If I use:

result <- try(sqlSave(ch,df,tablename="tblTest"))

I can use:

if (class(result) != "try-error")

to check if something went wrong. No problem.

But if I use try in combination with a function it doesn't work as I expected:

 result <- try(ch<-odbcConnect("TEST"))

gives "-1" for result and "integer" for class(result)

So should I use

ch<-odbcConnect("TEST")
if (ch != -1)

and use geterrmessage() for the error message?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If you read closely error message you could see that odbcConnect gives you warning. Error is generated by ODBC drivers and it isn't error in try meaning (geterrmessage() won't work either).

You could use tryCatch to handle this, e.g.:

tryCatch(odbcConnect("TEST"), warning=function(w) print("FAIL!"))

Some more explanation:
-1 is a result of odbcDriverConnect function. If you look at the code there are lines

stat <- .Call(C_RODBCDriverConnect, as.character(connection), 
        id, as.integer(believeNRows), as.logical(readOnlyOptimize))
if (stat < 0L) {
     warning("ODBC connection failed")
     return(stat)
}

So you end without errors (and with a warning) and with integer code from C-level. Actually this code is returned when connection is succeed too (but then is equal 1). When there is no errors then result class can't be try-error.
It is not problem with try and functions but specific of this particular function (odbcDriverConnect).

You could of course use this behaviour as in your example

ch <- odbcConnect("TEST")
if (ch != -1)

With tryCatch you could do

tryCatch(ch<-odbcConnect("TEST"), warning=function(w) print("FAIL!"))

which creates ch variable when succeed and print message when failed.
Or

ch <- tryCatch(odbcConnect("TEST"), warning=function(w) {print("FAIL!");return(NA)})

which always creates ch variable but in case of failure there is NA value.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...