Peter
Peter

Reputation: 13485

Java: try-catch vs if-else for initialization: performance

I've heard it's a sin to use try-catch for anything that might be expected to happen in normal program flow, and that one should use if-else instead.

But, what about the case where we want to use it for initialization (an event that happens once and once only). You may want this when you initialization depends on the first incoming data, as in the following example:

class RunningVectorSum{

    double[] running_sum;

    public double[] add(double vec[]){

        try{
            for (int i=0; i<running_sum.length; i++)
                running_sum[i]+=vec[i];
        }
        catch(NullPointerException ex){
            running_sum = new double[vec.length];
            for (int i=0; i<running_sum.length; i++)
                running_sum[i] = vec[i];
        }
        return running_sum;
    }
}

In this case, should it be faster in the long run to use the try-catch vs using:

    public double[] add(double vec[]){
        if (running_sum==null)
            running_sum = new double[vec.length];
        for (int i=0; i<running_sum.length; i++)
            running_sum[i]+=vec[i];
        return running_sum;
    }

instead?

edit: Things I'm aware of:

Things I'm not aware of:

Upvotes: 1

Views: 124

Answers (2)

luk2302
luk2302

Reputation: 57124

Runtime exceptions like NullPointerException or ArrayIndexOutOfBoundsException are an indicator of a bug in your program because you as the developer screwed up. Not the user or some external factor but your code.

You should never try to catch them, you have to make sure they simply cannot occur. If they occur, track them down and fix your code to make sure they never occur again.

If running_sum must not be null, enforce that by adding a constructor, that takes the value as parameter and checks for non-null. Having a add method without anything to add the input to makes no sense.

Upvotes: 0

Eran
Eran

Reputation: 393851

It's bad practice to use exception handling for implementing your business logic. Exception handling is for handling exceptional cases.

In your specific example it is even clearer that using exception handling is wrong, since your are duplicating your code in the exception handler.

BTW, your method has another potential problem. You have no guarantee that in each call to add you'll receive an array of the same length, so you run the risk of ignoring some of the values passed to your method, or getting ArrayIndexOutOfBoundsException if vec is shorter than running_sum.

Upvotes: 7

Related Questions