LoginSignup
22
22

More than 5 years have passed since last update.

Rでの例外処理(tryCatchの使い方メモ)

Last updated at Posted at 2014-04-15

用語

Rでは、signalされたconditionをhandleすることで、例外を処理する。

基本

  • 失敗するかもしれない処理を、tryCatchのexpr引数に渡す(この処理の返り値が、tryCatchの返り値になる)
  • 例外情報は、conditionクラスのオブジェクトの中にまとめられて、signalされる
  • 例外を捕まえるには、tryCatchの「...」引数に、「捕まえるconditionのクラス=handler」を渡す
  • finallyに、後始末を書く

要するに

こう書く

sample.r
tryCatch(失敗するかもしれない処理,
         error=エラーを処理する関数,
         message=メッセージを処理する関数, etc...
         finally=finallyな処理)

ODBC接続文字列とクエリを受け取り、DBに接続して、sqlを投げる。失敗したら、エラーと共に、接続文字列・クエリを表示。最後に、接続を切る。

try_sql.r
library(RODBC)

try.sql <- function(con.str, sql){
    tryCatch({
        con <- odbcDriverConnect(con.str)
        sqlQuery(con, sql)
    },
             error=function(e){
                 print(sprintf("Query failed:
connection string=%s
sql=%s
",
                               con.str, sql))
                 print(e)
             },
             finally=odbcCloseAll()
             )
}
22
22
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
22
22