If you invoke a Kotlin function that throws an exception and doesn't declare it with @Throws
, that crashes the app. Declared exceptions are converted to NSError and must be handled.
In Kotlin, all exceptions are unchecked. In Swift, all exceptions are checked. Therefore, it's important that Kotlin functions that may throw an exception be marked with the @Throws
annotation and the relevant exceptions. These exceptions will be represented as NSError
s and must be caught and handled.
In Kotlin:
@Throws(Exception::class)
fun functionThrowsDeclaredException(){
throw Exception("Oops!")
}
In Swift:
do {
try ExceptionsErrorsKt.functionThrowsDeclaredException()
}
catch {
print (error)
}
However, calling the following code from Swift will cause a program termination:
fun functionThrowsUndeclaredException(){
throw Exception("Oops!")
}
Suspend functions' completion handlers always have an error parameter. If a suspend function is not annotated with @Throws
, only CancellationExceptions are propagated as NSError.