0

I was working on a program, a basic one that is based on command line input. I made a custom exception which should be triggered when users don't enter the second input, but whenever I do so, it throws array out of bound exception. What should I do in this situation?

package com.company;
    
public class Program2 {


    public static void main(String[] args)  throws MYex{
        {
            int a,b,c;
        try
        {
            a=Integer.parseInt(args[0]); // getting data
            b=Integer.parseInt(args[1]); // from command line


            if( args[1]==null){
          throw new MYex();
          }

             try
            {
                c=a/b;
                System.out.println("Quotient is "+c);
            }

            catch(ArithmeticException ex)
            {
                System.out.println("Error in division !");
            }

        }
        catch (MYex e){
            System.out.println(e.toString());
        }
        catch(ArrayIndexOutOfBoundsException e)
        {
            System.out.println("Array out of bound!");
        }

        finally
        {
            System.out.println("End of the progarm!!!");
        }

    }

}}
  class MYex extends Exception{
    @Override
    public String toString() {
        return  " oops a Exception occured";
    }
}

 
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
ANDRO MAN
  • 1
  • 1

1 Answers1

0

If the user passes only one argument the args array has only one element. Therefore the exception already occurs when you try to access args[1].

To prevent this check args.length before accessing args[1]:

            a=Integer.parseInt(args[0]); // getting data
            if (args.length == 1) {
                throw new MYex();
            }
            b=Integer.parseInt(args[1]); // from command line
Thomas Kläger
  • 17,754
  • 3
  • 23
  • 34
  • Thanks man it worked for me ,also I updated ArrayIndexOutOfBoundsException if arguments are greater than 2 , as array should be taking only two arguments in this case. – ANDRO MAN Jul 31 '21 at 03:25