What style do professional programmers use when using try and catch or adding error handling in their code?

Which one is preferable to the other? Example:

class Example {
    int[] A = new A[5];

    void setArray(int item, int index) {
        if(index < 0 || index >= 5) {
            System.out.println("Index out of bounds");
        } else {
            A[index] = item;
        }
    }
}

      

or this one?

class Example {
    int[] A = new A[5];

    void setArray(int item, int index) {
        try {
            A[index] = item;
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("Index out of bounds");
        }
    }
}

      

+3


source to share


3 answers


When the language has good support for exceptions (like C # and Java), throwing and trapping is the most common way to handle exceptions.

The reason is that it makes the logic of the code clearer: methods can be written for the general case (without having to fix error codes, etc.), and only a few methods that actually have enough context to handle the unusual case will also contain the code for this.

Your example does not show what I am saying because you caught the exception at the same level where it happened. In practice, exceptions are useful because they are thrown several levels higher, some of them even reaching the top level of the program, interrupting all methods that will subsequently be called by this level.

The following explanation will hopefully shed some light on the importance of exceptions when used appropriately:

First of all, consider that the error message array index out of bounds

is meaningless to the user. Even just displaying a different type of error message, like one statement the file being read has an incorrect format

, is much more useful, even if it was inferred (by your program) from the fact that the array was accessible out of bounds. But you can't just change the error message in the set

array method because that doesn't make any sense - an array is used for a lot of things, and trying to index out of bounds can mean a lot of different things (depending on how the stream is reached there) ... Only a method that is high enough in the calling hierarchy knows what each kind of exception really means.



Second, if you move exceptions a few levels higher, your program can reason better about the problem and perhaps try a different course of action, perhaps without bothering the user at all.

Third, catching the exception and displaying the error message at such a low level prevents the caller's method from knowing that the exception happened at all. This means that the higher-level logic of the program will continue its normal flow as if nothing had happened, assuming that every operation has been successful so far. This is a kind of misbehavior and can range from relatively harmless to destructive.

So, to answer your question, the usually correct (practical) approach for the specific example in your question would be simply

void setArray(int item, int index) {
    A[index] = item;
}

      

and you will have to handle the exception at a higher level. If you want a general way to decide what to do in these cases, read my answer here .

+3


source


ArrayIndexOutOfBoundsException

- an exception at runtime.



Throwing IllegalArgumentException

in the first piece of code that sanitizes the input makes more sense.

+2


source


Exceptions, not particularly noted, apply to exceptional cases. If you can predict the point of failure, confirm the entry yourself. The only exception for me is NumberFormatException

, as this is obviously difficult to verify.

Unhandled exceptions are meant to be used when the API user might not be able to recover, but you obviously can in that case.

+1


source







All Articles