But if you use try!
it won't log the error so it will make it hard
to debug. No?
Correct. If I deployed this app to a wide number of users and found that this line was failing regularly, I might change my approach (either to log the error or attempt a recovery). In this case, however, Iâm pretty darned sure that an error from FileManager.url(for:in:appropriateFor:create:)
is not my fault, and the most useful diagnostic here would be a sysdiagnose log for the relevant folks at Apple to look at.
try!
is crashing the process?
Correct.
I want to double check because I fell this is quite severe.
That depends on your context. In a typical iOS app, crashing the process generally isnât a big deal. The user relaunches your app and continues on with their work. If thereâs a possibility that the user might lose a significant amount of work, you should already have a strategy in place for persisting that.
Keep in mind that, if you continue running when things are completely hosed â like, in my example, where FileManager.url(for:in:appropriateFor:create:)
has failed â itâs unlikely that youâll continue much further. Unless youâre fanatical about validating all of your error handling code paths, youâll likely run into a bug in one of them. Additionally, itâs possible that the original failure was collateral damage from some underlying failure, and that will cause other failures elsewhere in your process. If you continue running you could crash somewhere else, perhaps in framework code, something thatâs much harder to debug.
Thereâs a balance to be struck here:
-
How probable is the error?
-
What are the consequences of crashing?
-
How likely is it that youâll be able to do any useful recovery?
-
How likely is it that youâll make things worse by attempting a recovery?
-
How much does it cost you to write and test all that error handling code?
The answer here is different for each program and for the various errors within that program. My point is that crashing early is a valid option in some circumstances.
Finally, I want to stress that you shouldnât get too hung up about the presence of a !
. Many folks get worried by someArray.first!
but wouldnât bat an eyelid at someArray[0]
, even though the latter is more worrying IMO (because if someArray
is actually an array slice, the first index wonât be 0).
Share and Enjoy
Quinn âThe Eskimo!â @ DTS @ Apple