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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With