Is it somehow possible to handle a fatal error (of any kind) in iOS? I am not looking for some magical way to make the app stay alive, just some way to inform the user that something went wrong before the app disappears (like an alert for example).
4 Answers
A fatal error is a runtime error. You do not catch fatal errors, because they indicate a programming error, you should fix your code instead. Crashes are built in such a way so that you cannot stop them unless you fix the error in your code. Letting the user know that something went wrong cannot be done and wouldn't help anyway, unless you make it work properly.
To prove that they cannot be stopped, unless you change your code, we can put something that would cause a fatal error in a do-try-catch
structure:
do{
var car: String? = nil
try print(car!)
}
catch{
print("Something went worng")
}
Obviously, this still crashes with:
fatal error: unexpectedly found nil while unwrapping an Optional value.
So you must repair your program instead.

- 4,719
- 5
- 26
- 44
-
I get it, that's way I wrote that I am not looking for a way to stop the app from crashing. I am just wondering if there's some kind of way to perform some code before the app crashes. Basically what I would like to achieve is to somehow "observe" the crash event, on the crash event present an alert to user, then on user clicking OK -> proceed to crash – user3581248 Jun 26 '17 at 11:30
-
1@user3581248 You cannot. – Mr. Xcoder Jun 26 '17 at 11:31
-
Why the downvote? – Mr. Xcoder Jun 27 '17 at 08:34
While there is no way to inform the user directly of the error, since you would be printing in the console, using a guard statement will help you to avoid fatal errors by checking if the optional value exists in the first place, and returning early if the optional value does not exist. This will save your app from crashing at times.

- 11
- 2
When something goes wrong like unwrapping nil
, two situation may happen. If there are correct try catch around and the error is caught, then your app will continue working. Otherwise, you will end up having a fatal error that crash your app. So a fatal error is a consequence of lacking exception handling and is not something you can stop and show user something before the crash happens.

- 24,551
- 6
- 100
- 90
Just like others mentioned, fatal errors should NEVER occur. Do everything you can to prevent that error from happening.
You can prevent them using do catch
blocks and by handling optionals correctly. I would recommend you to read Apple's documentation on that! Good luck!

- 1,432
- 13
- 20