Jtest logo




Contents  Previous  Next  Index

OPT.CS


Close stream in "finally" blocks

Description

This rule flags code where the last "catch" block of a "try" statement does not contain a "finally" block.

Programs using certain types of resources should release them in order to avoid resource leaks. This can be done through a "finally" block which is placed after the last "catch" block of a "try" statement. Regardless of the outcome of the program, the "finally" block gets executed.

Example

 import java.io.*;
 
 package OPT;
 
 public class CS {
     public static void main (String args[]) {
         CS cs = new CS ();
         cs.method ();
     }
 
     public void method () {
         try {
             FileInputStream fis = new FileInputStream ("CS.java");
             int count = 0;
             while (fis.read () != -1)
                 count++;
             System.out.println (count);
             fis.close ();
         } catch (FileNotFoundException e1) {
         } catch (IOException e2) {
         }
     }
 }

Repair

Add a "finally" block after the last "catch".

Reference

Haggar, Peter. Practical Java - Programming Language Guide. Addison Wesley, 2000, pp. 77 -79.


Contents  Previous  Next  Index

ParaSoft logo
(888) 305-0041 info@parasoft.com Copyright © 1996-2001 ParaSoft