回答:
メソッド「def」は「begin」ステートメントとして機能します。
def foo
...
rescue
...
end
do/ endブロックリテラルは、暗黙の例外ブロックを形成します。
rescue TypeError; rescue NameErrorまたは例外クラスをコンマで区切ることができます。例:rescue TypeError, NameError
インラインでレスキューすることもできます。
1 + "str" rescue "EXCEPTION!"
「EXCEPTION!」「文字列はFixnumに強制できません」から
StandardErrorとそのすべてのサブクラスのように、良い習慣ではありNameErrorません。たとえば、コードのタイプミスがあってもエラーは発生しません。thoughtbot.com/ blog / don-t - inline-rescue - in-を参照してください。ルビー。
例:
begin
# something which might raise an exception
rescue SomeExceptionClass => some_variable
# code that deals with some exception
ensure
# ensure that this code always runs
end
ここでdefは、beginステートメントとして:
def
# something which might raise an exception
rescue SomeExceptionClass => some_variable
# code that deals with some exception
ensure
# ensure that this code always runs
end