Rubyは**begin/rescue/ensure**で例外を処理します(Rubyにおけるtry/catch/finallyと同等)。で例外を発生させ、で捕捉し、でクリーンアップを行います。Rubyはより簡潔なコードのために、明示的ななしでメソッドレベルのrescueも許可しています。
Rubyは**begin/rescue/ensure**で例外を処理します(Rubyにおけるtry/catch/finallyと同等)。で例外を発生させ、で捕捉し、でクリーンアップを行います。Rubyはより簡潔なコードのために、明示的ななしでメソッドレベルのrescueも許可しています。
raiserescueensurebeginbegin
result = risky_operation
rescue ArgumentError => e # rescue a SPECIFIC exception type
puts "Bad argument: #{e.message}"
rescue StandardError => e # broader catch (StandardError, not Exception)
puts "Error: #{e.message}"
retry if attempts < 3 # retry can re-run the begin block
else
puts "succeeded" # runs if NO exception
ensure
cleanup # ALWAYS runs (success or failure)
end
begin/rescue/ensureはRubyのtry/catch/finallyです。特定の型をrescueし(rescue ArgumentError)、ensureを保証されたクリーンアップのために使用し、elseをエラーがない場合に使用します。retryでブロックを再試行できます。
rescue => e # ✅ bare rescue catches StandardError (the right default)
rescue StandardError # ✅ explicit, same thing
rescue Exception # ❌ AVOID — catches EVERYTHING including system signals
# (Interrupt/Ctrl-C, SystemExit) — can break the program
重要です: 裸のrescueはStandardError(アプリケーションエラーの正しいデフォルト)を捕捉します。Exception(ルート)をrescueすると、すべてを捕捉します。これにはInterrupt(Ctrl-C)やSystemExitなどのシステムレベルのシグナルも含まれます。通常、プログラムが割り込まれたり終了したりするのを防ぐため、これらは捕捉したくありません。Rubyでよくある間違いです。
raise ArgumentError, "Amount must be positive" # raise a built-in
raise "Something failed" # raises RuntimeError
# custom exception class
class InsufficientFundsError < StandardError # inherit from StandardError
def initialize(msg = "Not enough funds")
super
end
end
raise InsufficientFundsError
def process
do_work
rescue => e # rescue WITHOUT begin — applies to the whole method body
handle(e)
ensure
cleanup
end
適切な例外処理はRubyアプリケーションの堅牢性に不可欠であり、Rubyの特定のイディオムと注意点を含むRubyのアプローチを理解することが重要です。
begin/rescue/ensure構造(Rubyのtryとcatchとfinally)、特定の例外型をrescueすること、ensureを保証されたクリーンアップのために使用すること、そして明示的なbeginなしの簡潔なメソッドレベルのrescueは、基本的な日常知識です。
特に重要で明確にRubyに特有な点は、StandardError対Exceptionの区別です。裸のrescue(および正しいデフォルト)はStandardErrorを捕捉しますが、Exception(階層のルート)をrescueするとすべてを捕捉します。これにはInterrupt(Ctrl-C)やSystemExitなどのシステムシグナルも含まれます。これはほぼ決して望まれません。プログラムが割り込まれたり終了したりするのを防ぎ、有害で一般的な間違いだからです。
アプリケーションエラーにはStandardError(Exceptionではなく)をrescueすべきであることを理解することは、実際のバグを防ぐ重要なRuby固有の知識です。
構造、カスタム例外クラス(StandardErrorを継承)、retry、メソッドレベルのrescueイディオム、そして特にStandardError対Exceptionの注意点を知ることは、エラーを優雅に処理し、プログラムの割り込み可能性を損なわない堅牢で正確なRubyを書くために重要です。
未処理のエラーとException-rescueの間違いは両方とも実際の問題を引き起こすため、Rubyの例外処理をマスターすることは重要で、その構造、イディオム、そして重大なStandardError対Exceptionの区別は、信頼性の高いRuby開発のための頻繁に関連する知識であり、一般的なインタビュートピックです。