Lets say we have an app that we are about to submit to the app store... but it contains the following code:
try? audioSession.setCategory(AVAudioSessionCategoryAmbient)
if error != nil {
// this should never happen
}
try? audioSession.setActive(true)
if error != nil {
// this should never happen
}
We have to "try" the setCategory method because it "throws" ... but I have no idea why it would ever throw/fail.
I feel like this will be viewed as trash code... and that I should be doing more than just saying "this should never happen," but if an error did happen, I would have no idea what to do with it.
This documentation doesn't give any reasons why there would be an error, either.
Am I supposed to make a pop-up window that says "sorry... we encountered an error while attempting to set the category on the audioSession singleton instance... but the reason for this error is beyond this app's control. Press OK so the app can close. This never happened during app testing... so I have no idea why it happened to you now... must have something to do with your device. Maybe reboot? Better luck next time."
Or am I supposed to "elegantly handle the error?" How can I do that when I don't know what the potential error "throws" are and more importantly the potential reasons behind them.
Thanks for any suggestions. :)
I see two strategies that you could adopt.
Assume that the only way to throw an error is to pass in an invalid category string. Since your string is hard coded to one of the supplied constants, you can assume this will never happen. In this case, make the try
cause a fatal error if it throws. e.g.
try! audioSession.setCategory(AVAudioSessionCategoryAmbient)
or
do
{
try audioSession.setCategory(AVAudioSessionCategoryAmbient)
}
catch
{
fatalError("setCategory failed with error: \(error)")
}
Assume there may be some local reason why it hasn't worked. In this case, use a do ... catch
to catch the error and report it to the user. This doesn't have to happen in the function that calls audioSession.setCategory
, you can choose to allow it to throw
and allow other functions in the call stack to throw until you get to a point where you can easily report the error. If you get to this point, make sure the intermediate throwing functions are capable of clearing up their state by using defer
and catch
blocks.