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?
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, 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