1. 正常情况下的资源泄露
FileOutputStream fos = newFileOutputStream(new File("test.txt"));
...
fos再也没有被关闭。
2. 异常情况下的资源泄露
1)
FileOutputStream fos = newFileOutputStream(new File("test.txt"));
fos.write(7); // write()发生异常,导致fos.close()没有被执行。
fos.close();
2)
FileOutputStream fos1 = newFileOutputStream(new File("test1.txt"));
FileOutputStream fos2 = newFileOutputStream(new File("test2.txt"));
fos1.close(); // close()发生异常,导致fos2没有close。—— close()会调用flush(),所以可能抛出异常。
fos2.close();
Java的try/catch的异常机制,是一种checked exception机制。目的是用来报告程序执行时出现的错误。
当异常发生时,程序不能继续执行,会退出。在这样的情况下探求“资源泄露”,意义不大,是舍本逐末的做法。