Kang-min Liu <
gu...@gugod.org> writes:
> 談到要把把錯誤狀態從函式中傳出來,基本上有兩種方式。有不少函式庫傾向使用
> die,但把錯誤狀況作為傳回值的一部分的作法也很常見。
在 Exception 與 error code 的這個題目上有不少好文章可以讀。跟 Emacs vs
vi 一樣是個長年爭議題。各有優劣,但沒什麼固定答案。:
# Exception vs Status returns. By Ned Batchelder:
=>
https://nedbatchelder.com/text/exceptions-vs-status.html
Exceptions are better.
- Clean code
- Valuable channels (not using valuable channels on passing errors)
- Richer error information
- Implicit code (implicit function calls that cannot be checked for return values.)
# Joel on Software article 13. By Joel Spolsky:
=>
https://www.joelonsoftware.com/2003/10/13/13/
Status return is better
- exceptions to be no better than “goto’s”,
- exceptions are invisible in the source code.
- exceptions create too many possible exit points for a function
# Perl, OO-based Exception (Arun Udaya Shankar):
=>
https://www.perl.com/pub/2002/11/14/exception.html
Exception is better
- Error handling code can be separated from normal code
- Less complex, more readable and more efficient code
- Ability to propagating errors up the call stack
- Ability to persist contextual information for the exception handler
- Logical grouping of error types
- Sins of omission (human nature)
# Rust vs go. Bby Ty Overby
=>
https://tyoverby.com/posts/rust-vs-go.html
Error as value. (Status returns).
這兩個較新的語言都不採用 Exception,而是採用 status returns。只是兩者都
有提供 panic 函式能帶著錯誤訊息立即跳離目前函式。雖然這函式的用法就跟丟
出Exception 是一樣的,但在 caller 端的錯誤處理方面與處理 Exception 不同。
caller 無法直接忽略不管,必須要寫幾行算式去對應到有錯誤發生的狀況。無法
有一個「錯誤處理中心」自動處理目前 call stack 底下好幾層的發生的錯誤。
---