简体   繁体   English

Kotlin文件读取,使用块不捕获所有异常

[英]Kotlin File Reading, use block not catching all exceptions

I'm doing some file IO with Kotlin and wanted to use those great extension methods provided in the library 我正在使用Kotlin做一些文件IO,并希望使用库中提供的那些很棒的扩展方法

  val cacheDir = externalCacheDir
            File(cacheDir, "missingfile.dat")
                    .inputStream()
                    .use {
                       //Use the file in someway
                    }

So this works great when the file is present but if the file is missing, I get a FileNotFoundException . 因此,当文件存在时,这很有用,但如果文件丢失,我会收到FileNotFoundException

This is expected. 这是预料之中的。 But If I want to correctly handle it I end up breaking that awesome Kotlin syntax by wrapping it in another try catch 但是,如果我想正确处理它,我最终通过将其包装在另一个try catch中来打破那个令人敬畏的Kotlin语法

So I dug into the code a bit and looked at the inputStream() call 所以我挖了一下代码并查看了inputStream()调用

I see this 我明白了

public inline fun File.inputStream(): FileInputStream {
    return FileInputStream(this)
}

So I thought I'd make my own extension function that does this. 所以我想我会做自己的扩展功能来做到这一点。 Wraps in a try catch so at least its not visible when using it 尝试抓住,至少在使用它时不可见

fun File.inputStreamOrNull(): FileInputStream? {
    return try {
        FileInputStream(this)
    } catch (e: Exception) {
        null
    }
}

However, a null pointer exception is thrown within the use block 但是,在use块中抛出空指针异常

 val cacheDir = externalCacheDir
            File(cacheDir, "protsfasfasfaso.mams")
                    .inputStreamOrNull()
                    .use {
                      //Going to use null input stream :O 
                    }

However, the use block does not actually catch this even though the high order function is wrapped in a try catch too which ends up crashing the app 然而,即使高阶函数也包含在try catch中, use块实际上也没有抓住这个,这最终导致应用程序崩溃

public inline fun <T : Closeable?, R> T.use(block: (T) -> R): R {
    var closed = false
    try {
        return block(this)
    } catch (e: Exception) {
        closed = true
        try {
            this?.close()
        } catch (closeException: Exception) {
        }
        throw e
    } finally {
        if (!closed) {
            this?.close()
        }
    }
}

Anyone got any ideas about this one? 有人对这个有任何想法吗? I know the quick fix but is there a way around to keep that cool Kotlin style? 我知道快速解决方法,但有没有办法保持酷酷的Kotlin风格? Thanks for reading 谢谢阅读

您可以将.use { ... }调用更改为空安全调用( ?. ),然后它将返回usenull的返回值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM