【问题标题】:Creating custom java exception [duplicate]创建自定义java异常[重复]
【发布时间】:2019-02-28 01:40:43
【问题描述】:

所以我设置了基础。我们需要创建一个用户指定大小的数组。一旦创建了数组,用户必须用整数值填充数组。然后程序应该执行链接图像中指定的算术运算 2。我又制作了两个数组,一个保留求和的答案,一个保留除法的答案。现在的问题是,当您需要对数组中的最后一个数字进行加法或除法时,我会得到一个 IndexOutOfBoundsException,因为在最后一个数字之后没有值可以加法或除法。他们对其进行了设置,以便它可以通过异常,因为这个实验室是关于异常和制作自定义异常的。但是我需要帮助做两个例外。如果用户在数组中输入非整数值,则第一个例外。第二个是 IndexOutOfBoundsException 异常。我不知道该怎么做。我将在下面添加我的代码

import java.util.Scanner;
import java.util.Arrays;

public class Driver {

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        int arrSize = 0;
        int num = 0;

        System.out.println("Enter array size");
        arrSize = input.nextInt();

        int[] numbers = new int[arrSize];
        int[] sum = new int[arrSize];
        int[] divide = new int[arrSize];

        for (int i = 0; i < numbers.length; i++) {
            System.out.println("Enter number");
            num = input.nextInt();
            numbers[i] = num;
        }

        for (int q = 0; q < numbers.length; q++) {
            sum[q] = numbers[q] + numbers[q+1];
            divide[q] = numbers[q] / numbers[q+1];
        }

        System.out.println(Arrays.toString(sum));
        System.out.println(Arrays.toString(divide));
    } 
}

【问题讨论】:

  • 这段代码和自定义异常有什么联系?
  • 看看这个如何创建自定义异常的链接。 mkyong.com/java/java-custom-exception-examples你需要创建一个继承java.lang.Exception的类
  • 数组访问问题也可以通过在访问前检查索引来避免

标签: java custom-exceptions


【解决方案1】:

这应该有助于您扫描整数值。

try{
    System.out.print("Enter an integer: ");
    int number = input.nextInt();  
    }
    catch (InputMismatchException ex) {
        System.out.println("Incorrect input: an integer is required)");
        //It's also possible to throw your custom Exception here, like "throw new CustomException();"
    }

关于 IndexOutOfBoundsException,只需在该区域周围编写一个 try catch 块,您期望该异常并抛出您自己的自定义异常。

try{
    ...
}catch(IndexOutOfBoundsException e){
    throw CustomException2();
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-25
    • 1970-01-01
    • 1970-01-01
    • 2012-01-15
    相关资源
    最近更新 更多