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?
If you read closely error message you could see that
odbcConnectgives you warning. Error is generated by ODBC drivers and it isn’t error intrymeaning (geterrmessage()won’t work either).You could use
tryCatchto handle this, e.g.:Some more explanation:
-1 is a result of
odbcDriverConnectfunction. If you look at the code there are linesSo 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
tryand functions but specific of this particular function (odbcDriverConnect).You could of course use this behaviour as in your example
With
tryCatchyou could dowhich creates
chvariable when succeed and print message when failed.Or
which always creates
chvariable but in case of failure there isNAvalue.