java - 循环处理异常

标签 java loops exception

我可以问一个关于我的头衔的问题吗?由于我是 java 的新手,我对程序中的异常处理有点困惑。我需要做的是,当用户输入错误的输入时,异常需要循环。对于下面的代码,它只执行 ArrayOutOfBounds 异常。为什么当我输入字符串/符号/小数值时,FormatNumberException 不执行。它仅显示在输出部分中,而不显示在 showMessageDialog 输出中。我尝试使用多个异常处理 Catch Multiple Java Exception还是一样。你能帮我解决这个问题吗?任何答案将不胜感激。抱歉我的英语不好。

public class TestRandomArray {

    public static void main(String[] args) {
        Random ran = new Random(); // create instant object from class Random.
        int array[] =new int[100]; //set an array variable with array size of 100
        int maxNumber = 150; //set the limit of the random number to generate

        for (int i = 0; i < array.length; i++) { 
            array[i] = ran.nextInt(maxNumber) + 1; //+1 means that the array number should not contain with 0 value. 1-150.
            //System.out.println(array[i]);                
        }
        //for(int i : array){
            //System.out.println(i + ",");  //this for method is other technique to print the list of array.
        //}        
            do {   
                    String input = JOptionPane.showInputDialog(null, "Enter index"); //Get input from user
                    int choosenIndex = Integer.parseInt(input); //change the string to int type.
                try {  
                    if(choosenIndex >= 0 || choosenIndex <= array.length)  
                        JOptionPane.showMessageDialog(null, "The value of choosen index in the array is : "
                        + array[choosenIndex]); //display the choosen index value.
                        System.exit(0);
                }catch (ArrayIndexOutOfBoundsException e){
                    if (choosenIndex < 0 || choosenIndex > array.length) {
                        JOptionPane.showMessageDialog(null,
                        "Index is out of bound. Enter from 0-99"); //display error for indexoutbound.
                    }
                }catch(NumberFormatException e){
                        JOptionPane.showMessageDialog(null, "Only integer allowed.");//display other error occured.
                }
            } while (true);
    }
}

最佳答案

Integer.parseInt(输入);

此语句位于 try block 外部。它必须位于内部,以便您的程序跳转到 catch(NumberFormatException e) block 。

关于java - 循环处理异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33387188/

相关文章:

java - 这个Java例程如何转换成Delphi?

java - 使用流将对象聚合到 Java 中的集合中

java - 我如何循环这个决策结构?

python - 尝试使用 while 循环计算 sqroot 时出现代码问题

java - MethodHandle - 必须被捕获或声明为抛出。为什么会出现这个错误?

java - 将 KeyEvent 发布到焦点组件

java - 没有合适的驱动程序 java.sql.SQLException

python - 根据我的列表输入重命名最后一个

python - 在 Python 中使用 "except Exception"与 "except ... raise"

c# - argument null异常和invalid异常怎么写?