throws Exception in finally blocks

后端 未结 15 2354
慢半拍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:36

    One solution, if the two Exceptions are two different classes

    try {
        ...
        }
    catch(package1.Exception err)
       {
        ...
       }
    catch(package2.Exception err)
       {
       ...
       }
    finally
      {
      }
    

    But sometimes you cannot avoid this second try-catch. e.g. for closing a stream

    InputStream in=null;
    try
     {
     in= new FileInputStream("File.txt");
     (..)// do something that might throw an exception during the analysis of the file, e.g. a SQL error
     }
    catch(SQLException err)
     {
     //handle exception
     }
    finally
     {
     //at the end, we close the file
     if(in!=null) try { in.close();} catch(IOException err) { /* ignore */ }
     }
    

提交回复
热议问题