開始ブロックと終了ブロックなしでRubyでレスキューを使用する方法


115

救助開始の標準的なテクニックを知っている

レスキューブロックを単独で使用する方法を教えてください。

どのように機能し、どのコードが監視されているかをどのようにして知るのですか?


回答:


223

メソッド「def」は「begin」ステートメントとして機能します。

def foo
  ...
rescue
  ...
end

3
また、クラス定義、モジュール定義、および(私が思う)do/ endブロックリテラルは、暗黙の例外ブロックを形成します。
イェルクWミッターク

def rescueを実行して、確実に終了することもできますか?
Mohamed Hafez 2013

確実にdef rescueを実行して終了を確認することもできます:-)
Antony

defで複数のレスキューを使用できますか?
marriedjane875

@ marriedjane875はい複数のレスキューを明示的に(各レスキュー句/ブロックを1行に1つずつ)使用するか、rescue TypeError; rescue NameErrorまたは例外クラスをコンマで区切ることができます。例:rescue TypeError, NameError
chemturion

48

インラインでレスキューすることもできます。

1 + "str" rescue "EXCEPTION!"

「EXCEPTION!」「文字列はFixnumに強制できません」から


1
例外のバックトレースをインラインでどのように救い、表示しますか?
Cyril Duchon-Doris

実際の例外を返す方法は?
user1735921 2017年

1
インラインレスキューは、レスキューStandardErrorとそのすべてのサブクラスのように、良い習慣ではありNameErrorません。たとえば、コードのタイプミスがあってもエラーは発生しません。thoughtbot.com/ blog / don-t - inline-rescue - in-を参照してください。ルビー
BrunoFacca

26

私はActiveRecord検証でdef / rescueの組み合わせをたくさん使用しています:

def create
   @person = Person.new(params[:person])
   @person.save!
   redirect_to @person
rescue ActiveRecord::RecordInvalid
   render :action => :new
end

これは非常に無駄のないコードだと思います!


19

例:

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
弊社のサイトを使用することにより、あなたは弊社のクッキーポリシーおよびプライバシーポリシーを読み、理解したものとみなされます。
Licensed under cc by-sa 3.0 with attribution required.