When to use exceptions in Java (example)

前端 未结 10 1915
既然无缘
既然无缘 2020-12-06 17:05

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){
         


        
10条回答
  •  无人及你
    2020-12-06 17:37

    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);
    }
    

提交回复
热议问题