回答:
メソッド「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