簡體   English   中英

Kotlin文件讀取,使用塊不捕獲所有異常

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

我正在使用Kotlin做一些文件IO,並希望使用庫中提供的那些很棒的擴展方法

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

因此,當文件存在時,這很有用,但如果文件丟失,我會收到FileNotFoundException

這是預料之中的。 但是,如果我想正確處理它,我最終通過將其包裝在另一個try catch中來打破那個令人敬畏的Kotlin語法

所以我挖了一下代碼並查看了inputStream()調用

我明白了

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

所以我想我會做自己的擴展功能來做到這一點。 嘗試抓住,至少在使用它時不可見

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

但是,在use塊中拋出空指針異常

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

然而,即使高階函數也包含在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()
        }
    }
}

有人對這個有任何想法嗎? 我知道快速解決方法,但有沒有辦法保持酷酷的Kotlin風格? 謝謝閱讀

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM