LoginSignup
1

More than 5 years have passed since last update.

RubyでCSVファイルを読み込むときのエラー処理パターン

Posted at

CSVファイルに予期しないデータが入っていて、読み込むプログラムがエラーになることはよくある。
そんなとき、エラーになった行番号が表示されると調査が楽になるので、以下のように書くのをパターン化するといいかもしれない。

require "csv"

filename = "hoge.csv"

CSV.foreach(filename).with_index(1) do |row, lineno|
  begin
    # 本処理
    puts row[0].gsub("a", "b")
  rescue
    # 元の例外にメッセージを付加して投げ直す
    raise $!, "#{filename}#{lineno} 行目を処理中にエラーが発生しました。\n#{$!.message}", $!.backtrace
  end
end

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
1