In the following Kotlin/JVM program System.exit(-1)
stops the execution of the program with an error exit code:
fun main(args: Array<String>) {
if (args.size < 2) {
println("too few args!")
System.exit(-1)
}
println("Hello, ${args[1]} from ${args[0]}")
}
Kotlin/Native does not have access to any Java classes, including System
. So what would the equivalent function be for a Kotlin/Native program to stop execution of the program with an error code?
In the following Kotlin/JVM program System.exit (-1) stops the execution of the program with an error exit code: fun main (args: Array<String>) { if (args.size < 2) { println ("too few args!")
And in SecondActivity the button, calls exitProcess (2) (Kotlin’s equivalent to Java’s System.exit ()) in order to terminate the app. Now let’s follow this use case: the user opens the app, clicks on the first button, the second activity is displayed and now she clicks on btn_action defined above. What will happen to the application?
It takes an exit code, which it passes on to the calling script or program. Exiting with a code of zero means a normal exit: We can pass any integer as an argument to the method. A non-zero status code is considered as an abnormal exit.
Calling the System.exit method terminates the currently running JVM and exits the program. This method does not return normally. This means that the subsequent code after the System.exit is effectively unreachable and yet, the compiler does not know about it.
Use exitProcess
:
import kotlin.system.exitProcess
...
exitProcess(exitCode)
Declaration and documentation in the Kotlin source code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With