2017-04-25 50 views
0

这里是处理异常红宝石中的异常处理 - 向下或在顶层?

首先

def prep_food 
    get_veggies() 
    get_fruits() 
rescue Exception => e 
    # => do some logging 
    # => raise if necessary 
end 

def get_veggies() 
    # gets veggies 
end 

def get_fruits() 
    # gets fruits 
end 

def prep_food 
    get_veggies() 
    get_fruits() 
end 

def get_veggies() 
    # gets veggies 
rescue Exception => e 
    # => do some logging 
    # => raise if necessary 
end 

def get_fruits() 
    # gets fruits 
rescue Exception => e 
    # => do some logging 
    # => raise if necessary 
end 

在顶层,其中作为第二种方式做它深处的第一个处理异常的方法有两种。 这两者之间有什么区别,程序员应该在什么时候选择它们?

回答

1

我更愿意将特殊情况解决为特定(rescue FooException而不是rescue Exception),并尽可能靠近它们可能引出的行(我的begin ... rescue块通常只包含一行)。

此外,我只从我能够并愿意处理的例外中拯救。如果我不能“修复”一个异常,捕捉它有什么意义?

说:我会选择你的秒示例。如果我必须以相同的方式处理相同类型的异常,那么我会考虑引入一个方法,该方法需要一个块并执行错误处理。例如:

def get_veggies 
    with_foo_error_handling do 
    # gets veggies 
    end 
end 

def get_fruits 
    with_foo_error_handling do 
    # gets fruits 
    end 
end 

private 

def with_foo_error_handling 
    begin 
    yield 
    rescue FooException => e 
    # handle error 
    end 
end 
+0

如果我不能“修复”一个异常,捕获它有什么意义? 我更喜欢自己去捕捉特定的例外。但在某些情况下,我会捕获所有异常并将它们写入日志,然后重新提升。这里只是一个例子,问题不是针对特定的异常,而是针对捕捉异常的位置。 – Vizkrig

+0

同意:记录和重新提升可能是处理异常的有效方法。在某些特殊情况下,即使忽略也可能会好起来。这取决于... – spickermann