Ruby 错误处理:如何正确抛出/捕获错误
我有一个调用其他两个方法的方法:Ruby 错误处理:如何正确抛出/捕获错误,ruby,Ruby,我有一个调用其他两个方法的方法: def first_method second_method # Don´t call this method when something went wrong before third_method end def second_method fourth_method fifth_method end 第二个方法调用其他方法: def first_method second_method # Don´t call thi
def first_method
second_method
# Don´t call this method when something went wrong before
third_method
end
def second_method
fourth_method
fifth_method
end
第二个方法调用其他方法:
def first_method
second_method
# Don´t call this method when something went wrong before
third_method
end
def second_method
fourth_method
fifth_method
end
假设第五种方法有一个begin/rescue语句:
def fifth_method
begin
# do_something
rescue Error => e
#
end
end
现在我想避免在第五个方法抛出错误时调用第三个方法。我/你如何在Ruby中最优雅地解决这个问题。我认为最简单的方法是从第五种方法中删除错误捕获,并将其移动到第一种方法
def first_method
begin
second_method
third_method
rescue Error => e
end
end
def fifth_method
# do_something
end
我认为最简单的方法是从fifth_方法中删除错误捕获,并将其移动到first_方法
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
请注意,您不应该从
exception
继承异常,因为这种类型的异常来自环境级别,其中StandardError
的异常用于处理应用程序级别的错误。我觉得这很明显,但无论如何
def first_method
begin
second_method
rescue
return
end
third_method
end
此构造(无显式异常类型)将捕获StandartError
异常
为了避免与其他异常交叉,您可以创建自己的异常类:
class MyError < StandardError; end
请注意,您不应该从
异常继承异常,因为这种类型的异常来自环境级别,其中标准错误
的异常用于处理应用程序级别的错误。如果您不想使用异常,您只需返回一个状态:
def fifth_method
# do_something
true
rescue Error => e
false
end
def first_method
if second_method
third_method
end
end
如果不想使用异常,只需返回一个状态:
def fifth_method
# do_something
true
rescue Error => e
false
end
def first_method
if second_method
third_method
end
end
我不明白,也许你应该阅读关于ruby异常的教程。我不明白,也许你应该阅读关于ruby异常的教程。