Java 将字符串识别为输入,如果不是整数则抛出异常

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22026301/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 13:08:08  来源:igfitidea点击:

recognize string as input and throw exception if not an integer

javacustom-exceptions

提问by user3353167

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

我是java新手,正在尝试做这个程序。基本上输入 3 个数字,它将计算一个立方体的体积。如果输入负数,则会引发异常,并且当输入超过 3 个时也会引发异常。如果输入不是数字,我也希望它抛出异常,但我不知道如何将输入存储在变量中,然后检查它是否是字符串并最终抛出异常。有什么建议?这是我的代码

     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       

采纳答案by jgitter

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.

如果所讨论的字符串不是整数的有效字符串表示形式,则已经抛出 NumberFormatException。

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

回答by Manoj Shrestha

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:

您的parseInt()方法会抛出您的自定义异常,如下所示:

    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 MyExceptionsimilar to other standard exceptions:

现在,您可以捕获MyException类似于其他标准异常的自定义异常:

       // 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