File.openは魔法の何もしていないが、基本的にそれだけであれば開始/、ブロックの最後にあなたのために自動的にファイルを閉じますこれ、確実にかかわらずに包まれたブロックとFile.newですブロックが正常に終了した場合、または内部で何らかの例外が発生した場合
Rubyコードの他の部分と同様に、File.openの場合は例外を処理する必要があります。 例外ハンドラチェーン内の他のハンドラによって例外を処理したり、厳密に処理したり、その場で処理することができます。この決定はFile.openとは無関係で、コード/アプリケーションとターゲットオーディエンスの性質と関連しています。たとえば、あなただけが実行するスクリプトを書いている場合は、例外をスライドさせてスタックトレースでスクリプトをクラッシュさせてもよいでしょう。他の場合には、もっと "プロフェッショナル"になりたいと思うでしょう。それは優雅なものです。その場合、ある時点で始動/救助を使わなければなりません。
ここでうまくいけばFile.open(それは基本的にRubyでRAII idiomだけの実装です)
File.open("foo") {|f|
# do something with the opened file
f.read
# once the block has finished, the file will be closed automatically
}
# File.open is essentially:
f = File.new "foo"
begin
yield f
ensure
f.close
end
# So in any case if you'd like to handle any exception that might be raised, just do the usual thing:
begin
File.open("foo") {|f|
# do something with the opened file
f.read
}
rescue
# handle all the exceptions - either coming from open/new or from inner file-handling block
end
begin
f = File.new "foo"
begin
# do something with the opened file
f.read
ensure
f.close
end
rescue
# handle the exceptions, using multiple rescue if needed to catch exact exception types like Errno::EACCES, etc
end
を分かりやすく説明するコードだあなたは、例外処理に有益な何かをするつもりですか?もしそうでなければ、単純なスクリプトでは大丈夫です。 – tokland
シリアル接続からデータを収集するループの一部です。私は自分の問題がシリアルポートだと思ったが、実際にはFile.openコマンドが失敗してしまった。 – Kenneth