简体   繁体   中英

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:

  • Yes in this particular example, there's a possible problem if vec has a varying length
  • Yes I know this is a terrible sin.

Things I'm not aware of:

  • Why is it such a terrible sin?
  • Is it faster to always pass through a try (except once, which amortizes to nothing) than it is to always pass through an if(condition)

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 .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM