NSException和NSError的使用場景

如果需要指出程序員的編碼錯誤,則應該使用NSException。例如,一個方法只能接收奇數(shù)作為參數(shù),但是程序員在調(diào)用該方法時傳入了一個偶數(shù),這時應該拋出異常,有點像斷言(Assert),方便調(diào)試程序。對于預期(expected)錯誤,如用戶錯誤和設備環(huán)境錯誤,應該使用NSError。例如,一個方法需要讀取用戶照片,但是沒有訪問權(quán)限,這時應該向方法調(diào)用者返回一個NSError對象,指出不能執(zhí)行的原因。

下面是官方文檔的說明

NSError is designed for non-fatal, recoverable errors. The problems that are designed to be captured by an NSError are often user errors (or are errors that can be presented to the user), can often be recovered from (hence -presentError: and NSErrorRecoveryAttempting), and are usually expected or predictable errors (like trying to open a file that you don't have access to, or trying to convert between incompatible string encodings).

NSException is designed for potentially fatal, programmer errors. These errors are designed to signify potential flaws in your application where you have not correctly checked the pre-conditions for performing some operations (like trying to access an array index that is beyond its bounds, or attempts to mutate an immutable object). The introduction to the Exception Programming Guide explains this a little bit

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容