Daniel
Daniel

Reputation: 2515

Using try/catch to break infinite loop

I just solved a fun little practice problem with basically boils down to this:

int [] array = new int [10];
int i = 0;
try{
  while (true){

     array[i++] = 10;

  }
}
catch(ArrayIndexOutOfBoundsException e){ 
   for(i = 0; i < 10; i++){
      System.out.println(array[i]);
   }
}

How evil is this? Goto evil? Lots of Global Variables evil? or is this totally fine?

Upvotes: 0

Views: 186

Answers (2)

A-SM
A-SM

Reputation: 884

Here are some possible ways to do it without try catch:

First

int [] array = new int [10];  
int i = 0;  

while(i<10){  
  array[i]=(i+1);  
  System.out.println(array[i]);  
  i++;
}  

Second

int [] array = new int [10];

for(int i=0; i<array.length; i++){
  array[i]=(i+1);
  System.out.println(array[i]);
}

What I mean is, if it's not really necessary to use try catch, don't! Try catch only supposed to prevent user error (usually in my program), or unless the program ask you to use it.

Upvotes: 0

Michael Gunter
Michael Gunter

Reputation: 12811

Exception handling is tremendously expensive in terms of performance (and somewhat expensive in terms of memory). As a general rule, you should always prefer other techniques where possible.

Upvotes: 2

Related Questions