Skip to content

Latest commit

 

History

History
42 lines (30 loc) · 1.23 KB

Exceptions.md

File metadata and controls

42 lines (30 loc) · 1.23 KB

Exceptions

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.

Explanations

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 NSErrors 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

Suspend functions' completion handlers always have an error parameter. If a suspend function is not annotated with @Throws, only CancellationExceptions are propagated as NSError.


Table of contents