CodeRed
11/16/2018, 3:42 PMfun writeSoundToSharedStorage(context: Context, sound: ISound): Boolean {
var inputStream: InputStream? = null
var outputStream: OutputStream? = null
val targetFile = getTargetFileFromSoundName(sound.soundName()) ?: return false
try {
inputStream = context.assets.open(getAssetPathFromSound(sound))
outputStream = FileOutputStream(targetFile)
inputStream.copyTo(outputStream)
} catch (ex: IOException) {
Log.e(LOG_TAG, "Failed to save file: ${ex.message}")
return false
} finally {
try {
inputStream?.close()
outputStream?.close()
} catch (ex: IOException) {
ex.printStackTrace()
}
}
return true
}
What I'm thinking about is to migrate the try-catch-finally-block to a use()-block. But from the docs of use() I'm not sure if exceptions are handled or not. I took a look into the implementation and for me it looks like an exception is thrown, so my guess would be that my app would crash as long as I don't handle it somehow. Also my function depends on returning false if something went wrong. It would be nice if someone could bring some more clarity to me 🙂diesieben07
11/16/2018, 3:47 PMuse
does is ensure that any thrown exceptions do not prevent your resource (Closeable
) from being disposed. It works basically the same as the try-with-resources
construct in Java.use
will ensure that close
is called in all cases.Mike
11/16/2018, 3:53 PMclose
would not get called.
try-with-resource/use really helps clean up the code BUT you still need to ensure you have enough of them.CodeRed
11/16/2018, 4:02 PMMike
11/16/2018, 4:05 PMdiesieben07
11/16/2018, 4:09 PMuse
like any other: You put try
around it 🙂CodeRed
11/16/2018, 4:25 PM@InlineOnly
@RequireKotlin("1.2", versionKind = RequireKotlinVersionKind.COMPILER_VERSION, message = "Requires newer compiler version to be inlined correctly.")
public inline fun <T : Closeable?, R> T.use(block: (T) -> R): R {
var exception: Throwable? = null
try {
return block(this)
} catch (e: Throwable) {
exception = e
throw e
} finally {
when {
apiVersionIsAtLeast(1, 1, 0) -> this.closeFinally(exception)
this == null -> {}
exception == null -> close()
else ->
try {
close()
} catch (closeException: Throwable) {
// cause.addSuppressed(closeException) // ignored here
}
}
}
}
Reinis
11/16/2018, 4:50 PMMike
11/16/2018, 5:33 PMthrows
for checked exceptions, not all exceptions.
Kotlin treats ALL exceptions as unchecked exceptions, so there’s no need to explicitly define that an exception is thrown.
Having said that, IF your code is called from Java, and you want the Java compiler to ‘do the right thing’, you can add the @Throws
annotation.CodeRed
11/16/2018, 7:34 PM