title: Using try-catch with a if else loop
body: <p>So I am making a program which takes an int input from the command line and then searches the array in the program for the int and if found, return the index of the number. If not, then it throws an exception stating that it wasn't found and end the program. This is what I have so far: </p>
  
  <pre><code>public static void main(String[] args) {
  
      int[] intArray = {9, 97, 5, 77, 79, 13, 7, 59, 8, 6, 100, 55, 35, 89, 74, 66, 32, 47, 51, 88, 23};
      System.out.println(Arrays.toString(intArray));
  
      int intArgs = Integer.parseInt(args[0]);
  
      System.out.println("Your entered: " + intArgs);
  
      FindNum(intArray, intArgs);
  }
  
  public static int FindNum(int[] intArray, int intArgs) {
      for (int index = 0; index &lt; intArray.length; index++){
          try{
              if (intArray[index] == (intArgs))
                  System.out.println("Found It! = " + index);
              else 
                  throw new NoSuchElementException("Element not found in array.");
          } catch (NoSuchElementException ex){
              System.out.println(ex.getMessage());
          }
      }
      return -1;      
  }
  </code></pre>
  
  <p>While this sort of works and can find the index, it throws the exception for each number in the array instead of just one for the whole array. And if it finds the number in the array, then it replaces one of the lines with the confirmation line from the loop. Example output for 66: </p>
  
  <pre><code>[9, 97, 5, 77, 79, 13, 7, 59, 8, 6, 100, 55, 35, 89, 74, 66, 32, 47, 51, 88, 23]
  Your entered: 66
  Element not found in array.
  Element not found in array.
  Element not found in array.
  Element not found in array.
  Element not found in array.
  Element not found in array.
  Element not found in array.
  Element not found in array.
  Element not found in array.
  Element not found in array.
  Element not found in array.
  Element not found in array.
  Element not found in array.
  Element not found in array.
  Element not found in array.
  Found It! = 15
  Element not found in array.
  Element not found in array.
  Element not found in array.
  Element not found in array.
  Element not found in array.
  </code></pre>
  
  <p>How can I make it so that when it finds the number, it only prints the index line and vice versa for the exception. I feel it may have something to do with the loop but not sure what I can do to prevent that. </p>