错误处理:如何抛出/捕获错误正确

问题描述:

我有一个调用其它两种方法的方法:错误处理:如何抛出/捕获错误正确

def first_method 
    second_method 

    # Don´t call this method when something went wrong before 
    third_method 
end 

的second_method调用其他方法:

def second_method 
    fourth_method 
    fifth_method 
end 

Let's说fifth_method有一个开始/救援声明:

def fifth_method 
    begin 
    # do_something 
    rescue Error => e 
    # 
    end 
end 

现在我想避免third_method被调用时,five_method抛出一个错误。我将如何在Ruby中最优雅地解决这个问题。

我认为最简单的方法是消除错误从fifth_method捕获,并将其移动到first_method

def first_method 
    begin 
    second_method 

    third_method 
    rescue Error => e 

    end 
end 


def fifth_method 
    # do_something 

end 

在我看来那么明显,但无论如何

def first_method 
    begin 
    second_method 
    rescue 
    return 
    end 
    third_method 
end 

这种结构(没有明确的类型的例外)将捕获StandartError例外。

为了避免交叉点与另一个例外,你可以创建自己的异常类:

class MyError < StandardError; end 

,然后用它

begin 
    second_method 
rescue MyError => e 
    return 
end 

请注意,你不应该从Exception继承例外,因为这种类型的例外来自环境级别,其中StandardError的例外旨在处理应用程序级错误。

+1

我不明白,或许你应该阅读有关Ruby异常的教程。 – megas 2012-08-17 10:47:36

如果你不想使用异常,你可以返回一个状态:

def fifth_method 
    # do_something 
    true 
rescue Error => e 
    false 
end 

def first_method 
    if second_method 
    third_method 
    end 
end