我有一个调用另外两个方法的方法:
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
假设 fifth_method 有一个 begin/rescue 语句:
def fifth_method
begin
# do_something
rescue Error => e
#
end
end
现在我想避免在 fifth_method 抛出错误时调用 third_method。我/你如何在 Ruby 中最优雅地解决这个问题。
最佳答案
在我看来很明显,但无论如何
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
的异常旨在处理应用程序级别的错误。
关于ruby - 错误处理 : How to throw/catch errors correctly,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12002347/