Rails的錯誤處理機制begin、rescue和Exception
5 min readFeb 21, 2018
在執行程式的時候,我們不免都會遇到例外的處理方式,在Rails中我們可以輕易地透過begin-end的block和rescue來處理例外產生的情況。
begin
# 可能出現例外的程式碼
rescue ScriptError
# 出現ScriptError時執行此程式碼
rescue ArgumentError
# 出現ArgumentError時執行此程式碼
rescue SomeOtherException
# 出現SomeOhterException時執行此程式碼
end
什麼是begin-end block?
begin來自於Object類別,基本上和end一起使用,主要是用來處理例外產生的機制,常被統稱為begin block或是begin-end block。
什麼是rescue?
rescue可以用來指派錯誤處理的子句,當沒有指定Exception類別的話,就會直接執行。
begin
# 可能出現例外的程式碼
rescue
# 沒有指定Exception的類別的話,那就是出現錯誤就執行
end
也可以指定需要回應的Exception類別以及想要傳入的local variable。
begin
raise ArgumentError, "1234.0"
rescue ArgumentError => error
puts error.inspect
end
什麼是exception?
簡單的來說就是程式執行時出現了某個預料外的結果(exception:例外),而在Ruby中出現exception時,基本上只會有兩種情況:
- 如果begin-end block中沒有提供rescue的話,終止程式執行
- 執行rescue 子句(clause)中的程式碼
在Rails中exception是來自於Exception類別或是Exception子類別的實體。在Exception類別中羅列了各種可能會產生例外的情況,像是SyntaxError、ArgumentError、RuntimeError等等。
什麼是raise?
在不實際執行一段會有exception的程式碼的情況下,我們也可以手動產生exception的實體來觸發我們想要的結果,在這邊我們透過使用raise這個method來執行。
raise是來自於Kernel這個module的method,預設會產生來自RuntimeError這個類別的exception實體。
def raise_exception
puts "Before the raise method"
raise "An error has occurred"
puts "After the raise"
endraise_exception
#=> "Before the raise method"
#=> RuntimeError: RuntimeError
如果不想使用預設的RuntimeError,我們可以使用raise指定exception的類別和報錯訊息。
def raise_exception
puts "Before the raise method"
raise ArgumentError, "報錯"
puts "After the raise"
endraise_exception
#=> "Before the raise method"
#=> ArgumentError: 報錯
參考資料:raise
其他參考資料