How to catch the dreaded "uncaught exception"?

I'm working on an engineering app that uses a bunch of java code I succefully converted using J2OBJC. Amazing! I can call the functions defined in that java code from my Swift code and it works nicely most of the time.


But that java code throws an "OutOfRangeException" whenever the user input paramaters fall out of some range. The error ends up in my AppDelegate and crashes my app there.


Is there a way to catch this "exception" gracefully without crashing?


I've tried the following but it doesn't work, as Xcode warns:

do {        'catch' block is unreachable because no errors are thrown in 'do' block
    let myVar = JavaProject().someFunction(with: Temp)            
     } catch {
  }


*** Terminating app due to uncaught exception 'OutOfRangeException', reason: 'JavaProject.OutOfRangeException'

>Is there a way to catch this "exception" gracefully without crashing?


No, not when the example involves a landmine named 'exception', as Swift has no mechanism to catch all arbitrary runtime exceptions.


Once the process gets that far, the damage to app stability is done.

There is no way to catch Objective-C exceptions (NSException) in Swift.

So, if the converted Objective-C code throws exceptions on OutOfRangeException or any other cases Java code throws,

You cannot catch such "exception".


do-catch catches Error in Swift, it has nothing to do with Objective-C exceptions.

You may need to touch all the converted Objective-C code which may throw exceptions.


You can write an Objective-C wrapper to catch the exceptions and convert it to errors which Swift can handle,

but even in Objective-C, once exception thrown, the app may be in an unpredictable state and may not be able to continue running.


Or you may need to check the the user input paramaters not to fall out of some range.


Else, you may need to wait for J2Swift or something would be practically available. Though I do not know it is planned.

You probably thought of it already…


Is the error du to temp value ?


Have you a way to predict what should be incorrect temp, before calling someFunction ?

That's exactly what I was doing when the problem was uncovered. I was mapping out how to validate that user inputs are in the proper range, so I could catch them all in Swift and never trigger the exception. The java code documentation describes a range of parameter values but I encountered this problem well inside that range. I've contacted the author.

If you contact the author, you could ask him/her to modify to fail without crashing when out of range. That would make your task easier…

How to catch the dreaded "uncaught exception"?
 
 
Q