Jtest logo




Contents  Previous  Next  Index

OPT.TRY


Place "try/catch" blocks outside of loops

Description

This rule flags any "try/catch" block inside a loop.

Placing "try/catch" blocks inside loops can slow down code execution.

If "try/catch" blocks are inside loops, code execution can be about 20 percent slower if the JIT compiler is turned off on a JVM without a JIT.

Example

 package OPT;
 import java.io.FileInputStream;
 
 public class TRY {
     void method (FileInputStream fis) {
         for (int i = 0; i < size; i++) {
             try { // violation
                 _sum += fis.read();
             } catch (Exception e) {}
         }
     }
     private int _sum;
 }

Repair

Place "try/catch" block outside of the loop.

     void method (FileInputStream fis) {
         try {
             for (int i = 0; i < size; i++) {
                 _sum += fis.read();
             }
         } catch (Exception e) {}
     }

Reference

Haggar, Peter. Practical Java - Programming Language Guide. Addison Wesley, 2000, pp.81 - 83.


Contents  Previous  Next  Index

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