Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why use an exception instead of if...else

For example, in the case of "The array index out of bound" exception, why don't we check the array length in advance:

 if(array.length < countNum)
 {
 //logic
 }
 else
 {
 //replace using exception
}

My question is, why choose to use an exception? and when to use an exception, instead of if-else

Thanks.

like image 785
DNB5brims Avatar asked Nov 17 '11 01:11

DNB5brims


People also ask

Can I use try-except instead of if-else?

Most of the people don't know that Try-Except block can replace if-else (conditional Statements). Yes, You read it right! It can be done. We can use Try ( Exception Handling ) instead of using normal conditional statements.

Is try-except better than if?

If you expect your code to encounter the error condition less often the non-error condition, then try... except is better. If you expect your code to encounter the error condition more often than the non-error condition, then if...else is better.


1 Answers

It depends on acceptable practices for a given language.

In Java, the convention is to always check conditions whenever possible and not to use exceptions for flow control. But, for example, in Python not only using exception in this manner is acceptable, but it is also a preferred practice.

like image 75
Dmitry B. Avatar answered Jan 03 '23 14:01

Dmitry B.