Best way to check arguments before running a method

So, for example, if I had a method called "divide" and it just divided by ints and returned an int, that would be the best way to verify that the divisor is! = 0

Method 1:

    private int divide(int i1, int i2) {
         if(i2 == 0) return 0;

         return i1/i2;
}

Method 2:

    private int divide(int i1, int i2) {
        if(i2 != 0) {
            return i1/i2;       
        } else {
            return 0;
        }
    }

Which one do you prefer?

EDIT: I know that you usually don't write such a function as it throws an exception if the divisor is 0. This is just to clarify my question.

EDIT 2: I just changed the method function to return 0 if the divisor is 0.

+4
source share
9 answers

If your goal is to throw away RuntimeExceptionwhen the second argument 0, you don't need to do anything.

private int divide(int i1, int i2) {
    return i1/i2; // This will throw an ArithmeticException
}

ArithmeticException, RuntimeException, RuntimeException.

: , .

else, , , else - , , return, .

if, , else , , return , , , return .

private int divide(int i1, int i2) {
    if(i2 == 0) {
        return 0;
    }
    return i1/i2;
}
+1

( , ) , , . .

+1

, , , i2 == o, .

+1

, , ,

private int divide(int i1, int i2) {
    if(i2 != 0) {
        return i1/i2;
    } else {
        throw new RuntimeException();
    }
}

? u Alert int.

+1

, RuntimeException ; Exception. , , , (java.lang.ArithmeticException) RuntimeException.
, - ?

private int divide(int i1, int i2) throws DivisionByZeroException {
    try {
        return i1/i2;
    } catch(ArithmeticException e) {
        throw new DivisionByZeroException(e);
    }
+1
private int divide(int i1, int i2) throws IllegalArgumentException{
    if(i2==0)
    throw new IllegalArgumentException("Argument 'divisor' is 0");
    else return i1/i2;
}
0
0

, - , , .

However, I must say: always double check if such a check is necessary.

In your particular case, check redundant, since division by 0 will cause ArithmeticExceptionwho says / by zero.

See this question for a brilliant explanation of why checks are often exaggerated, especially with null / non-null checks.

0
source

Use the method below. You do not need to check for zero. Just highlight arithmetic exception.

private int divide( int i1, int i2 ) throws ArithmeticException
{
    return i1/i2;
}
0
source

Source: https://habr.com/ru/post/1535733/


All Articles