开发者

Handling an exception properly

I am not good at handling exceptions, so I need a hint at this occasion: I want to put arrays in a collection (ArrayList) all of which should be of the same length. Otherwise errors emerge in computations. When an array of not desired length is to be inserted in the ArrayList, I would like to throw a开发者_开发问答n exception with a message. What kind of exception is suitable for this occasion?

What worries me is that I have to check the size of the array which is to be inserted (with an if statement). Is it reasonable to have an if statement inside a try block?

Here is the relevant fragment code:

inputdata: the arrayList

arraylength: the length of the array specified by the first array inserted

Could somebody modify the try - catch block?

public void insertData(double[] arraydata){
    if(this.inputdata.isEmpty()){
        inputdata.add(arraydata);
        this.arraylength = arraydata.length; 
    }else{
        try {
           if(this.arraylength == arraydata.length)
               inputdata.add(arraydata);
        }catch(Exception exception){
            System.err.printf("Missmatch array dimensions in %d place",inputdata.size()+1);           
        }
    }
}


Exceptions should only be for exceptional cases. If this is a frequent occurrence, you might want to handle it another way, with standard logic in the workflow. For example, you could retur n true if you can insert the data, and false if the array to insert is not the right length. Or you could check when the user enters the array values, and tell them then that the length has to be x.

If this does represent an exceptional case throw an IllegalArgumentException, as in

if(this.arraylength == arraydata.length)
    inputdata.add(arraydata);
} else {
    throw new IllegalArgumentException("Ever array needs same length...");
}

something like that.

As written, your code right now is catching any exception thrown in the add operation. You should throw, instead of catch, an exception in your insertData method, as my example demonstrates. The exception should be caught outside of the insert data method. This means you don't need a try/catch statement in insertData.

Also note that IllegalArgumentException is a Runtime exception, so it does not need to be thrown or caught if you don't want to. You still can catch it, if you want.


What you are doing in

    try {
       if(this.arraylength == arraydata.length)
           inputdata.add(arraydata);
    }catch(Exception exception){
        System.err.printf("Missmatch array dimensions in %d place",inputdata.size()+1);           
    }

Is catching an exception. But inputdata.add is not going throw any exception. Instead, you should throw an exception so that the callers know something is wrong:

   if(this.arraylength != arraydata.length)
       throw new IllegalArgumentException("Array length " + arraydata.length 
           + " is not same as previous length " + this.arraylength);
   inputdata.add(arraydata);

The exception includes a helpful message to let the caller know what the mismatch is.

Note that I have reversed the test, if the legnth is not acceptable then Exception is thrown; otherwise the execution proceeds to next line.


What exception is suitable? Depends. Here are some things to consider.

  1. Is this code part of a method, and was it the intent that the user have the responsibility to pass an array of the right size? The caller made a mistake, so use an IllegalArgumentException.
  2. Is this code part of a larger line of code, and was it the intent that the code would have constructed correctly sized arrays? One of your assumptions is wrong, so use an IllegalStateException.
  3. The situation of wrong-sized arrays is legitimate in some way, and your handler will repair the situation at some level, then continue. I would roll my own Exception for this case.

Your code seems to be case (1). The answers provided show some good ways to handle this. I like to use Guava Preconditions myself, since they are self-documenting and less error-prone (no if-statements just to direct the execution around error conditions that require maintenance -- just add new checkSomething calls where they make sense):

import static com.google.common.base.Preconditions.checkArgument;

<snip>

public void insertData(double[] arraydata) {
    checkArgument(this.arraylength == arraydata.length,
            "Ever array needs same length...");
    inputdata.add(arraydata);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜