2009-10-09 30 views

回答

189

的方法 “高清” 可以作为一个 “开始” 声明:

def foo 
    ... 
rescue 
    ... 
end 
+0

谢谢,我只是想知道这是如何工作的。这几乎是我正在寻找的。谢谢。 – Sid 2009-10-10 06:47:22

+2

另外,类定义,模块定义和(我认为)'do' /'end'块文字形成了隐含的异常块。 – 2011-10-22 11:25:06

+0

你可以做高清救援吗? – 2013-09-23 03:02:12

41

您也可以拯救内嵌: “EXCEPTION”

1 + "str" rescue "EXCEPTION!" 

会打印出因为“串不能强迫Fixnum对象”

+1

如何解救并显示异常回溯内联? – 2017-05-24 15:15:33

+0

如何返回实际的异常? – user1735921 2017-06-22 12:30:34

21

我使用DEF /救援组合了很多与ActiveRecord的验证:

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

我觉得这是非常精简的代码!

14

例子:

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