Search code examples
javaarraysexceptionjavac

Custom exception not running , throwing other exception but not customly defined. What should I do for custom Exception?


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

 

Solution

  • 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