title: iOS - Catching exceptions in main()
body: <p>So, I had an idea to <strong>catch</strong> unanticipated <strong>exceptions</strong> in <strong>main</strong> and try to cleanup and exit gracefully:</p>
  
  <pre><code>int main(int argc, char *argv[])
  {
      @autoreleasepool
      {
          //return UIApplicationMain(argc, argv, nil, NSStringFromClass([GRWAppDelegate class]));
          @try
          {
              int retVal = UIApplicationMain(argc, argv, nil, NSStringFromClass([GRWAppDelegate class]));
              return retVal;
          }
          @catch (NSException *exception)
          {
              [Utilities setPreferencesDefaults];
          }
      }
  }
  </code></pre>
  
  <p>This does catch exceptions and updates the preference defaults.</p>
  
  <p>I then thought, why exit at all, just cleanup and relaunch, so I wrapped everything in a while loop:</p>
  
  <pre><code>int main(int argc, char *argv[])
  {
      while (YES)
      {
          @autoreleasepool
          {
              ...
          }
      }
  }
  </code></pre>
  
  <p>Of course I wouldn't be here if that actually worked. Problem is, once it again executes</p>
  
  <pre><code>retVal = UIApplicationMain(argc, argv, nil, NSStringFromClass([GRWAppDelegate class]));
  </code></pre>
  
  <p>it immediately throws a new exception:</p>
  
  <pre><code>Assertion failure in void UIApplicationInstantiateSingleton(Class)(), /SourceCache/UIKit/UIKit-2380.17/UIApplication.m:2037
  
  NSInternalInconsistencyException
  @"There can only be one UIApplication instance."
  </code></pre>
  
  <p>Makes sense, so is there a way I can discard the existing singleton and replace it with a new one? (although I guess it's not really a singleton if I can)</p>
  
  <p>Purpose is, I don't ever want the app to crash giving a bad user experience. Even if their state isn't completely restored, I would think that would still be better than just unexpectedly exiting.</p>
  
  <p>I can try to handle possible expected exceptions, but this is to try to catch things that I haven't foreseen.</p>
  
  <p>This should really only catch VERY unusual circumstances, so if it can't be done it's not that big of a deal, but I was wondering how best to deal with this type of situation.</p>