Cleanup with finally and NonCancellable
Release resources in cancelled coroutines using finally and withContext(NonCancellable).
Cleanup with finally and NonCancellable is a free Kotlin Academy lesson on CoddyKit — lesson 3 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Kotlin Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
Cancellation and finally
When a coroutine is cancelled, suspension points throw CancellationException. Code in finally blocks always runs — but finally itself runs in a cancelled coroutine context.
import kotlinx.coroutines.*
fun main() = runBlocking {
val job = launch {
try {
delay(1000)
} finally {
println("finally: cleaning up")
}
}
delay(50)
job.cancel()
job.join()
}Problem: Suspension in finally
If you try to delay or do another suspension inside finally of a cancelled coroutine, it throws immediately because the context is already cancelled.
import kotlinx.coroutines.*
fun main() = runBlocking {
val job = launch {
try {
delay(1000)
} finally {
// delay(100) // throws CancellationException here!
println("Sync cleanup OK; async cleanup needs NonCancellable")
}
}
delay(50); job.cancel(); job.join()
}withContext(NonCancellable)
Wrap suspension calls in finally with withContext(NonCancellable) to run them in a non-cancellable context even after the parent is cancelled.
import kotlinx.coroutines.*
fun main() = runBlocking {
val job = launch {
try {
delay(1000)
} finally {
withContext(NonCancellable) {
delay(100) // OK: runs despite cancellation
println("Async cleanup complete")
}
}
}
delay(50); job.cancel(); job.join()
}When to Use NonCancellable
Use NonCancellable for: closing DB connections, flushing logs, sending analytics events, or any async cleanup that must complete regardless of cancellation.
import kotlinx.coroutines.*
suspend fun closeConnection() {
println("Closing DB connection...")
delay(50) // simulate async close
println("Connection closed")
}
fun main() = runBlocking {
val job = launch {
try { delay(1000) }
finally { withContext(NonCancellable) { closeConnection() } }
}
delay(50); job.cancel(); job.join()
}NonCancellable is Not a Scope
NonCancellable is a Job you can pass to withContext. Do not use it as a coroutine scope directly — use it only in finally cleanup.
import kotlinx.coroutines.*
fun main() = runBlocking {
// WRONG usage:
// launch(NonCancellable) { ... } // launches a coroutine that cannot be cancelled
// RIGHT usage:
launch {
try { delay(500) }
finally {
withContext(NonCancellable) {
println("Safe cleanup")
}
}
}.also { delay(50); it.cancel(); it.join() }
}Multiple Resource Cleanup
Chain multiple cleanup operations inside a single withContext(NonCancellable) block.
import kotlinx.coroutines.*
fun main() = runBlocking {
launch {
try {
delay(1000)
} finally {
withContext(NonCancellable) {
delay(20); println("Step 1: flush cache")
delay(20); println("Step 2: close socket")
delay(20); println("Step 3: log audit")
}
}
}.also { delay(50); it.cancel(); it.join() }
}try/catch/finally Pattern
Combine try-catch for business errors with finally for cleanup — this is the standard structured pattern.
import kotlinx.coroutines.*
fun main() = runBlocking {
launch {
try {
delay(100)
throw RuntimeException("business error")
} catch (e: RuntimeException) {
println("Handling: ${e.message}")
} finally {
withContext(NonCancellable) {
println("Always cleanup")
}
}
}.join()
}Cleanup Ordering
Finally blocks run in reverse order of nesting. Outer try-finally runs after inner ones, just like in regular Java/Kotlin code.
import kotlinx.coroutines.*
fun main() = runBlocking {
launch {
try {
try {
delay(1000)
} finally { println("Inner cleanup") }
} finally { println("Outer cleanup") }
}.also { delay(50); it.cancel(); it.join() }
}use() for AutoCloseable Resources
For AutoCloseable resources, use Kotlin's use { } extension which calls close() automatically, even on exceptions or cancellation.
import kotlinx.coroutines.*
class Connection : AutoCloseable {
init { println("Opened") }
override fun close() { println("Closed") }
suspend fun query(): String { delay(50); return "result" }
}
fun main() = runBlocking {
val result = Connection().use { it.query() }
println(result)
}Logging Cancellation Reason
Retrieve the cancellation message from CancellationException in catch or finally to log why a coroutine stopped.
import kotlinx.coroutines.*
fun main() = runBlocking {
val job = launch {
try {
delay(1000)
} catch (e: CancellationException) {
println("Cancelled: ${e.message}")
throw e
}
}
delay(50)
job.cancel("user navigated away")
job.join()
}CoroutineScope Cleanup with invokeOnCompletion
Job.invokeOnCompletion registers a callback that runs when the job finishes for any reason — an alternative to finally for parent-level cleanup.
import kotlinx.coroutines.*
fun main() = runBlocking {
val job = launch {
delay(1000)
}
job.invokeOnCompletion { cause ->
if (cause != null) println("Ended with: ${cause::class.simpleName}")
else println("Completed normally")
}
delay(50)
job.cancel()
job.join()
}Quick Check
What is the purpose of withContext(NonCancellable) in a finally block?
Recap
finally always runs on cancellation. Wrap suspension calls inside finally with withContext(NonCancellable) so they complete despite cancellation. Use use { } for AutoCloseable resources.
Frequently asked questions
Is the “Cleanup with finally and NonCancellable” lesson free?
Yes — the full text of “Cleanup with finally and NonCancellable” is free to read here on the web, and the Kotlin Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Kotlin Academy course, upgrade to CoddyKit PRO.
What will I learn in “Cleanup with finally and NonCancellable”?
Release resources in cancelled coroutines using finally and withContext(NonCancellable). You practise Kotlin Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Kotlin Academy?
No prior experience is required. Kotlin Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 3 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Cleanup with finally and NonCancellable” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Kotlin Academy lesson?
Yes. Every Kotlin Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- Cooperative Cancellation: isActive and ensureActive
- withTimeout and withTimeoutOrNull
- Cleanup with finally and NonCancellable
- Cancellation Propagation in Coroutine Hierarchies