Maximillian
Maximillian

Reputation: 1614

Is it better to catch run-time exception than condition judgement previously to avoid exception

Say, the codes below may throw run-time exception when divisor is zero.

try {
    int result = dividend / divisor;
} catch (Exception e) {
    Log.d("exception:" + e);
}

or we can write as below.

if (divisor != 0) {
    int result = dividend / divisor;
} 

I am confused which one is more reasonable and why?

--------------------------------------------- update ---------------------------

I have a new idea that if a method want to provide divide function.

public int divide(int dividend, int divisor) throws ArithmeticException {
    if (divisor == 0) {
         throw new ArithmeticException("divide by zero");
    }

    return dividend / divisor;
}

In the caller,

try {
    int result = divide(dividend, divisor);
} catch (Exception e) {
    Log.d("exception:" + e);
}

or

if (divisor != 0) {
    int result = divide(dividend, divisor);
} 

Regardless of performance, both seems no problem. Isn't it?

Upvotes: 2

Views: 201

Answers (3)

oycarlito
oycarlito

Reputation: 122

The second code block is the better when dealing with math calculations.

Upvotes: 0

Sweeper
Sweeper

Reputation: 273978

Definitely use conditionals when you can!

Throwing and catching exceptions is very slow, much slower than checking whether some number is equal to 0. The same goes for ArrayIndexOutOfBoundsException (checking whether the index is greater than 0 and less than length of array), NullPointerException (check if the object is null), NumberFormatException (check if a string is in the correct format before calling things like Integer.parseInt).

Error handling is not for flow control. When you use try...catch, you are handling something you really can't control. Many methods have checked exceptions, and those are the exceptions you should catch.

Upvotes: 2

Shubhendu Pramanik
Shubhendu Pramanik

Reputation: 2751

If you have only one if condition then if (divisor != 0) is reasonable but imagine multiple divisions where their value may change at run time then so many if-else is headache and exception(may be your custom) is better approach.

Hope this helps.

Upvotes: 1

Related Questions