I know that this would be bad practice although I know that I would not be able to explain why.
int [] intArr = ...
...
try{
int i = 0;
while(true){
System.out.println(intArr[i++]);
}
}catch(ArrayIndexOutOfBoundsException e){}
I think that you are only supposed to use exceptions for things that shouldn't happen. I am asking this question because I think that I am using exceptions wrong sometimes. If your programming is running a standard case should exceptions be thrown?
This seems related: Preventing exceptions vs. catching exceptions in Java
It's wrong because you know that eventually the loop will reach the last element of intArr
, so there's nothing exceptional in this, you're actually expecting this behaviour.
You are right: exceptions are meant for, ehm, exceptional cases. Using them for controlling normal control flow is not only obscuring the intent of the code (which would be enough to disqualify it already), but also is much slower, since throwing and catching exceptions is costly.
The standard idiom (in Java5 and above) is using a foreach loop:
for (int i : intArr) {
System.out.println(i);
}
Catching exceptions is only a bad practice when it concerns a RuntimeException
. The ArrayIndexOutOfBoundsException
which you're trying to catch there is one.
RuntimeExceptions
identify programmatically recoverable problems which are caused by faults in code flow. You should not fix them by catching them, but by writing proper code and making use of flow control statements like if/else
, while
, for
, etc.
As always "it depends" and you will find many differing opinions. Here's mine
You would expect to generally handle the first category and not the latter. The latter is usually programming errors.
Your example falls into the latter case, a programming error. The exception is intended to give good information about the failure at runtime, not act as a control flow.
Some people will say that the first is checked exceptions and the second is unchecked. I would disagree with that. I almost always find checked exceptions a pain in reality as you almost always end up doing catch/wrap/rethrow to another exception type. When throwing exceptions and defining my own exception classes I almost always use unchecked.
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