Michael Krussel
10/13/2026, 12:34 PMval resource = Resource()
var completed = false
try {
// work that can throw
completed = true
return resource
} finally {
if (!completed) {
resource.close()
}
}
Seems more natural to cleanup in a catch block. Catching generic Exception because cleanup should happen even on unexpected RuntimeExceptions. Similar to wanting to use a use function, but only cleanup on failure, otherwise the caller cleans it up.
val resource = Resource()
@Supress("TooGenericExceptionThrown")
try {
// work that can throw
return resource
} catch (e: Exception) {
resource.close()
throw e
}CLOVIS
10/13/2026, 4:49 PMMichael Krussel
10/13/2026, 5:32 PMThrowable .CLOVIS
10/13/2026, 5:36 PMCLOVIS
10/13/2026, 5:37 PMtry…catch if you're always going to rethrow the exceptionephemient
10/13/2026, 6:34 PMfinally form as well. it can't lose the exception if close failsMichael Krussel
10/13/2026, 6:46 PMephemient
10/13/2026, 6:50 PMfinally but trying it out locally, it's not happening in either case.CLOVIS
10/13/2026, 6:50 PMCLOVIS
10/13/2026, 6:51 PMMichael Krussel
10/14/2026, 12:03 PMuse function does it, but in a catch block. You need access to the exception to be able to add a new exception to it.