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 an 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
trueif you can insert the data, andfalseif 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 bex.If this does represent an exceptional case throw an IllegalArgumentException, as in
something like that.
As written, your code right now is catching any exception thrown in the
addoperation. You should throw, instead of catch, an exception in yourinsertDatamethod, 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 ininsertData.Also note that
IllegalArgumentExceptionis 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.