throws Exception in finally blocks

后端 未结 15 2352
慢半拍i
慢半拍i 2020-11-29 18:04

Is there an elegant way to handle exceptions that are thrown in finally block?

For example:

try {
  // Use the resource.
}
catch( Excep         


        
15条回答
  •  盖世英雄少女心
    2020-11-29 18:29

    I usually do it like this:

    try {
      // Use the resource.
    } catch( Exception ex ) {
      // Problem with the resource.
    } finally {
      // Put away the resource.
      closeQuietly( resource );
    }
    

    Elsewhere:

    protected void closeQuietly( Resource resource ) {
      try {
        if (resource != null) {
          resource.close();
        }
      } catch( Exception ex ) {
        log( "Exception during Resource.close()", ex );
      }
    }
    

提交回复
热议问题