title: Kotlin File Reading, use block not catching all exceptions
body: <p>I'm doing some file IO with Kotlin and wanted to use those great extension methods provided in the library</p>
  
  <pre><code>  val cacheDir = externalCacheDir
              File(cacheDir, "missingfile.dat")
                      .inputStream()
                      .use {
                         //Use the file in someway
                      }
  </code></pre>
  
  <p>So this works great when the file is present
  but if the file is missing, I get a <code>FileNotFoundException</code>.</p>
  
  <p>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</p>
  
  <p>So I dug into the code a bit and looked at the <code>inputStream()</code> call</p>
  
  <p>I see this</p>
  
  <pre><code>public inline fun File.inputStream(): FileInputStream {
      return FileInputStream(this)
  }
  </code></pre>
  
  <p>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</p>
  
  <pre><code>fun File.inputStreamOrNull(): FileInputStream? {
      return try {
          FileInputStream(this)
      } catch (e: Exception) {
          null
      }
  }
  </code></pre>
  
  <p>However, a null pointer exception is thrown within the <code>use</code> block</p>
  
  <pre><code> val cacheDir = externalCacheDir
              File(cacheDir, "protsfasfasfaso.mams")
                      .inputStreamOrNull()
                      .use {
                        //Going to use null input stream :O 
                      }
  </code></pre>
  
  <p>However, the <code>use</code> 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</p>
  
  <pre><code>public inline fun &lt;T : Closeable?, R&gt; T.use(block: (T) -&gt; 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()
          }
      }
  }
  </code></pre>
  
  <p>Anyone got any ideas about this one?
  I know the quick fix but is there a way around to keep that cool Kotlin style?
  Thanks for reading</p>