I'm seeing Claude writing cleanup on error code di...
# codereview
m
I'm seeing Claude writing cleanup on error code differently than what I would do.
Copy code
val 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.
Copy code
val resource = Resource()
@Supress("TooGenericExceptionThrown")
try {
  // work that can throw
  return resource
} catch (e: Exception) {
   resource.close()
   throw e
}
c
Should the resource be closed when no exception is thrown at all? Should the resource be closed when a fatal error is thrown?
m
It should be closed after the function returns on no exception. Ownership and cleanup responsibility is given to the caller. Any many of these cases the resource is stored in a field and closed sometime in the future. But the design is to make sure they are always cleaned up. When I do the catch, it is normally catching
Throwable
.
c
I personally prefer the second version with the regular
try…catch
if you're always going to rethrow the exception
e
I'd prefer the
finally
form as well. it can't lose the exception if
close
fails
m
If close fails, the both lose the original exception. With the catch, you can do something with suppressed exceptions on the JVM at least.
e
hmm. I thought JVM was supposed to attach the suppressed exception to
finally
but trying it out locally, it's not happening in either case.
🤔 1
c
I thought it did too 🤔
Oh maybe it's only in try-with-resources
m
The
use
function does it, but in a catch block. You need access to the exception to be able to add a new exception to it.