2012-08-17 98 views
1

我有一個調用其它兩種方法的方法:錯誤處理:如何拋出/捕獲錯誤正確

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中最優雅地解決這個問題。

回答

1

我認爲最簡單的方法是消除錯誤從fifth_method捕獲,並將其移動到first_method

def first_method 
    begin 
    second_method 

    third_method 
    rescue Error => e 

    end 
end 


def fifth_method 
    # do_something 

end 
3

在我看來那麼明顯,但無論如何

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

1

如果你不想使用異常,你可以返回一個狀態:

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

def first_method 
    if second_method 
    third_method 
    end 
end