Tuesday, June 28, 2005

assert 與 exception 使用時機

assert 用在 class 的 private method 中,用以檢查 class 自己的 internal state 是否正確。assert 也可用於同一 translation unit 內的 function 中。在這兩種情況,private method 或 function 被呼叫到的可能性是可自己掌握的,使用 assert 不會造成其他 client 的不快。

exception 用在 class 的 public method 中,因 public method 無法掌握被使用的時機與方式,若被呼叫時 internal state 有問題,則擲出 exception 告知 client 使用錯誤。exception 亦可用來檢查傳入之參數合法與否,若 public method 無法處理 client 傳入之參數,即擲出異常。上述擲出 exception 情形皆屬 severe,倘若傳入之參數合法,public method 正常運作,但因外部環境問題造成錯誤狀況發生,這時則可採傳回 error code,讓 client 以 error handling 方式處理錯誤。

No comments: