0

I have code like the following:

if let vc = NSStoryboard.main?.instantiateController(withIdentifier: someIdentifier) as? Self{
    return vc
}else{
    //handle error case
    return nil
}

And when it runs with an identifier that is not found in my storyboard, it does NOT go to the else case, but instead prints an error to console and immediately returns (does not crash). Because it behaves so much like an Error being thrown, I tried surrounding it with a do-catch like so:

do{
   if let vc = try NSStoryboard.main?.instantiateController(withIdentifier: someIdentifier) as? Self{
       return vc
   }
}catch{
   //handle error
}

But this gave me warnings that the method does not throw errors so the catch block would never be reached. I ran it anyway and sure enough the catch block was not reached. It instead printed the error to console and seemed to just return immediately.

Can someone explain to me what's going on here and how to 'catch' this error?

note: Just for clarification, I understand why the instantiation of the view controller fails, but I'm wanting to handle that error case dynamically. Thats the problem I'm having.

svaerth
  • 51
  • 1
  • 5
  • You shouldn't try to catch such an error programatically. This is basically a fatal error. If you are trying to load an invalid controller, it's a programming error. – Sulthan Mar 05 '20 at 13:51

1 Answers1

1

If you enable "All Objective-C Exceptions" break point in XCode you see it throws an Objective C exception and last time I checked, there was no safe way to recover from Objective-C exceptions in Swift.

Catching NSException in Swift

Jimmy
  • 1,405
  • 2
  • 14
  • 19