Use exceptions only for exceptions

original
2012/12/16 13:59
Reading number 315

Look at two pieces of code first

 //Exception based pattern String t1[]={"11","22"}; try{ int i=0; while(true){ System.out.println(t1[i]); i++; } }catch(ArrayIndexOutOfBoundsException e){ } //Standard mode for(String t:t1){ System.out.println(t); }
Why does someone prefer exception mode to standard mode?

They try to use the error judgment mechanism of Java to improve the performance. Because the VM needs to check the out of bounds condition for each array access, the normal termination test is considered redundant. There are three mistakes in this idea:

1. The exception mechanism is designed for abnormal situations. Few jvm implementations attempt to optimize them, making them as fast as the displayed test

2. Putting code in try catch prevents modern jvms from implementing specific optimizations that might otherwise be executed

3. The standard mode of variables for arrays does not lead to redundant checks. Some modern jvm implementations optimize them.


The exception based pattern not only obscures the purpose of the code and reduces its performance, but also cannot ensure its normal operation. For example, the following code:

 public static void main(String[] args) { String t1[]={"11","22"}; try{ int i=0; while(true){ System.out.println(t1[i]); test(); i++; } }catch(ArrayIndexOutOfBoundsException e){ } } private static void test(){ String t2[]={}; t2[0].toString(); }
The exception mode is used. When an exception related to this bug is generated, it will be caught and incorrectly interpreted as a normal loop termination condition.


A well-designed API should not force its client to use exceptions for normal control flow. There are two good API designs

1. Status test, indicating whether the method related to this status can be called. For example,

 for(Iterator<String> i=collection.iterator(); i.hasNext();) { String s=i.next() }
The Iterator interface has a "state dependent" next method and the corresponding state test method hasNext(). This makes it possible to use the traditional for loop to iterate over the collection

2. If the "state related" method is called and the object is in an inappropriate state, it will return a recognized value, such as null.

If the object will be accessed concurrently without external synchronization, or can be changed by the outside world, it may be necessary to use recognized return values.

If the separate "state test" method must repeat the "state related" work, the identifiable return value should be used from the perspective of performance. If the other aspects are equal, the "state test" method is slightly better than the identifiable return value.

Expand to read the full text
Loading
Click to lead the topic 📣 Post and join the discussion 🔥
Reward
zero comment
zero Collection
zero fabulous
 Back to top
Top