Hi all how can I handle objective-c exceptions in ...
# multiplatform
h
Hi all how can I handle objective-c exceptions in Kotlin Multiplatform using try/catch?
f
Please be more specific
h
In the iosMain we are using NSDecimal and when a String is invalid and we want to convert it to NSDecimal it throws NSDecimalNumberOverflowException which is not possible to catch it using try/catch
It seems there is a workaround to fix it which is using
Copy code
extraOpts = listOf("-Xforeign-exception-mode", "objc-wrap")
in the pod() block, but as we don't use any 3rd party libraries I'm not sure how I can use this workaround
a
NSDecimalNumberOverflowException
fires on the NSDecimal overflow - it looks like the number inside your string is too big. Maybe you need another type, line NSNumber. Also, using
try/catch
in Objective-C is not the preferred way of work anyway. I'd recommend either check the string before conversion or use another type.
h
Right, but I’m looking a way to catch objective-c exceptions in Kotlin
a
Let me clarify - The Objective-C language was not designed with Exception handling mechanism in mind. Because of that, every exception there is very undesirable and slow to handle. Much slower then exceptions in Kotlin Native or Swift. Even if you find the way to handle the exception - I won't recommend to do so because of performance reasons. It's better to find another solution rather then rely on the one you want to use.
👍 1
h
Thank you for the clarification. However, I’d like to better understand: do you mean that Objective-C exception handling in KMP has performance issues, or that exception handling has issues within Objective-C code itself? Objective-C natively supports try/catch, and JetBrains introduced ForeignException to allow catching Objective-C exceptions in Kotlin code. But this must be explicitly enabled in the pod() block. As I mentioned earlier, since I’m not using any third-party libraries, I can’t enable it. There is try/catch doc by Apple: https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/Exceptions/Tasks/HandlingExceptions.html