The Old New Thing 中關於 exception-safe 的相關討論:
- Cleaner, more elegant, and wrong
- How did MS-DOS report error codes?
- Cleaner, more elegant, and harder to recognize
如同我以前在 Assertions and Error Handling 這篇文章中的觀點,我還是認為 exception 帶來的好處多於它帶來的問題。大家都知道 “writing error handling code is hard”,不表示我們就可以忽略這個議題而不做 error handling;正如同 “writing bug-free code is hard” 不是你程式裡有一堆臭蟲的好理由。
關於 exception-safe 或是 failure atomicity 這個問題,常見的五個解決方法可以參考 Effective Java 中的 Item 46: Strive for failure atomicity:
- design immutable objects
- check parameters for validity before performing the operation
- order the computation so that any part that may fail takes place before any part that modifies the object
- write recovery code
- perform the operation on a temporary copy