自定义异常(RuntimeException)

时间:2014-03-23 17:58:31

标签: java exception custom-exceptions

我想做出自己的例外。但是,当我抛出异常时,程序就会关闭。那么如何运行我的方法3次,之后关闭程序。 (我的程序在intArray之后关闭,但我想通过dobleArray和charArray)

这是我的例外:

public class InvalidSubScriptException extends RuntimeException{

    public InvalidSubScriptException(){
        super("Invalid subscript");
    }
}

这是我的代码:

import javax.naming.spi.DirStateFactory;


public class GenericTest {

    public static void main(String[] args) {
        Integer[] intArray = {1, 2, 3, 4, 5};
        Double[] doubleArray = {1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7};
        Character[] charArray = {'H', 'E', 'L', 'L', 'O'};


        System.out.println("Array integerArray contains:");
        printArray(intArray);
        System.out.println("Array integerArray from possition 1 to 3 contains:");
        printArray(intArray, 1, 3);
        System.out.println("Array integerArray from possition -1 to 30 contains:");
        printArray(intArray, -1, 30);

        System.out.println("Array doubleArray contains:");
        printArray(doubleArray);
        System.out.println("Array doubleArray from possition 1 to 3 contains:");
        printArray(doubleArray, 1, 3);
        System.out.println("Array doubleArray from possition -1 to 30 contains:");
        printArray(intArray, -1, 30);

        System.out.println("Array charArray contains:");
        printArray(charArray);
        System.out.println("Array charArray from possition 1 to 3 contains:");
        printArray(charArray, 1, 3);
        System.out.println("Array charArray from possition -1 to 30 contains:");
        printArray(intArray, -1, 30);
    }

    public static <T> void printArray(T[] inputArray) {
        int counter = 0;
        for (T element : inputArray) {
            System.out.printf("%s ", element);
            counter++;
        }
        System.out.println();
        System.out.println(counter + " element(s) were output");
        counter = 0;
    }

    public static <T> void printArray(T[] inputArray, int lowSubscript, int hightSubscript) throws InvalidSubScriptException {
        int counter = 0;
        if (lowSubscript >= 0 && hightSubscript < inputArray.length) {
            for (int i = lowSubscript; i <= hightSubscript; i++) {
                System.out.printf("%s ", inputArray[i]);
                counter++;
            }
            System.out.println();
            System.out.println(counter + " element(s) were output");
            counter = 0;
        } else {
            throw new InvalidSubScriptException();
        }

    }
}

1 个答案:

答案 0 :(得分:1)

您要搜索的是如何捕获异常。在Java中,您可以使用try-catch子句执行此操作。

由于您的printArray()是引发异常的那个,因此您可以使用try-catch子句围绕对该方法的调用:

try {
    printArray(...);
    // ...
} catch (InvalidSubScriptException e) {
    // what you want to do to handle the exception
}