1

I'm new to java and was trying to do this program. Basically entering 3 numbers, it will calculate the volume of a cube. If a negative number is typed then it will throw an exception, and also when there are more then 3 input. I wanted it to throw an exception also, if the input is not a number, but I have no idea how to store the input inside a variable and then check if it's a string and eventually throw an exception. Any suggestions? Here's my code

     public class CubeVolume
     {
       public static void main(String [] args)
       {
         try
         {
           // try if there is more than 3 arguments 
           int width = Integer.parseInt(args[0]);
           int depth = Integer.parseInt(args[1]);
           int hight = Integer.parseInt(args[2]);
           if (args.length > 3)
           throw new ArrayIndexOutOfBoundsException
                 ("You have supplied " + args.length + " arguments!");

          // try if there is less than 3 arguments
          if (args.length < 3)
          throw new ArrayIndexOutOfBoundsException
              ("You have supplied " + args.length + " arguments!");                    

          // checks if the width entered is equal or less than 0
          if (width <= 0)
          throw new NumberFormatException
              ("The argument " + width + " is a negative number!");

          // checks if the depth entered is equal or less than 0
          if (depth <= 0)
          throw new NumberFormatException
              ("The argument " + depth + " is a negative number!"); 

          // checks if the hight entered is equal or less than 0
          if (hight <= 0)
          throw new NumberFormatException
              ("The argument " + hight + " is a negative number!");     


          int volume = width * depth * hight;
          System.out.println("The volume of a cube with dimensions " + "(" + width 
                             + "," + hight + "," + depth + ") " + "is " + volume);
         } // try

        // if there's one than more argument error will be displayed
        catch (ArrayIndexOutOfBoundsException exception)
        {
          System.out.println("Please supply width, depth and hight arguments!");
          System.out.println("Exception message was: '" + exception.getMessage() 
                             + "'");
          System.err.println(exception);
        } // catch          

       // if a negative number is entered error will be displayed
       catch (NumberFormatException exception)
       {
         System.out.println("Dimensions for a cube can't be negative, please "
                                   + "insert only positive whole numbers!");
         System.out.println("Exception message was: '" + exception.getMessage() 
                                   + "'");     
         System.err.println(exception);
       } // catch

     } // main
  } // CubeMain       
7
  • After glancing at the code I don't see any obvious errors. What problems are you having, specifically? Have you tried running it? Commented Feb 25, 2014 at 21:16
  • there's no problem, but I want to throw an exception if the input is not a number. So if it's a string would display an error message saying that is not possible to use a string, and I have no clue how to do it. Commented Feb 25, 2014 at 21:18
  • 1
    If you look at the spec, Integer.parseInt throws a NumberFormatException if the string does not contain a parsable integer. The only question would be whether you wanted to check for "junk" after the number, I think. Commented Feb 25, 2014 at 21:20
  • Integer.parseInt() throws an exception for you if the string is not an integer. You can catch it and throw your own custom exception if you want. Side note: You're checking that the length is 3 after having already accessed the 3rd argument. Commented Feb 25, 2014 at 21:21
  • How can i take the input from the console and check if it's not a number and throw an exception? because with that code if I enter a string, it will throw an exception giving the message: Dimensions for an object can't be negative, please insert only positive whole numbers! java.lang.NumberFormatException: For input string: "ciao" Exception message was: 'For input string: "ciao"' Commented Feb 25, 2014 at 21:36

2 Answers 2

3

This:

int width = Integer.parseInt(args[0]);

already throws a NumberFormatException if the String in question is not a valid string representation of an integer.

EDIT:

To address your comments:

public class CubeVolume {
   private int width;
   private int depth;
   private int height;

   public static void main(String [] args) {
       if (args.length != 3) {
           throw new Exception("Width, height and depth are required arguments");
       }
       width = Integer.parseInt(args[0]);
       depth = Integer.parseInt(args[1]);
       height = Integer.parseInt(args[2]);

       // more stuff here
   }
}
Sign up to request clarification or add additional context in comments.

16 Comments

is it possible to do throw a custom exception?
Also, I highly recommend that you don't "repurpose" existing java exceptions. Either throw generic Exceptions or create new specific exception classes.
Yes, it is possible to throw custom exceptions. Just create a class that extends Exception. .... Then throw it.
if I run it and let's say i type 'hello' into the console, it will catch the exception for the negative numbers, so it will display: Dimensions for an object can't be negative, please insert only positive whole numbers! java.lang.NumberFormatException: For input string: "ciao" Exception message was: 'For input string: "ciao"'
that is because you are catching NumberFormatException in your outer try/catch block and throwing a new exception with a different message.
|
-1

You can create your own exception class and throw the instance of that class from a method.

The exception class:

// Extending Exception makes your class throwable
class MyException extends Exception {

    public MyException( String string ) {
        super( string );
    }
}

And for parsing the input string to integer, call a method like this :

int width = parseInt(args[0]);

where your parseInt() method throws your custom exception as follows:

    private int parseInt( String number ) throws Exception {
        try {
            return Integer.parseInt( number );
        } catch ( Exception e ) {
            throw new MyException( "The input is not a number" );
        }
    }

Now, you can catch your custom exception MyException similar to other standard exceptions:

       // catching your custom exception
       catch ( MyException e ) {
            System.err.println( e );
        }

        // if there's one than more argument error will be displayed
        catch (ArrayIndexOutOfBoundsException exception)
        {
          System.out.println("Please supply width, depth and hight arguments!");
          System.out.println("Exception message was: '" + exception.getMessage() 
                             + "'");
          System.err.println(exception);
        } // catch          

       // if a negative number is entered error will be displayed
       catch (NumberFormatException exception)
       {
         System.out.println("Dimensions for a cube can't be negative, please "
                                   + "insert only positive whole numbers!");
         System.out.println("Exception message was: '" + exception.getMessage() 
                                   + "'");     
         System.err.println(exception);
       } // catch

2 Comments

-1 Don't catch the general Exception class. Also, creating an unique class is redundant as it is doing the same thing as the NumberFormatException. Also, I have no idea when you would ever catch a NumberFormatException given your code.
is it possibile to do it within one class? and if yes, could you show me how please?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.