如果需要指出程序員的編碼錯誤,則應該使用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