Java ArrayIndexOutOfBoundsException的自定义异常

Java ArrayIndexOutOfBoundsException的自定义异常,java,exception,Java,Exception,我有一个自定义异常扩展异常,但是它似乎没有捕获ArrayIndexOutOfBoundsException。但是,如果我将catch子句改为catchException,它将按预期工作 超类异常是否应该捕获子类异常,即使它是运行时异常 以下是异常的原因: int timeInMillis = 0; for (int i = 0; i < commandMessage.length; i++) for (String commandValue : command.g

我有一个自定义异常扩展
异常
,但是它似乎没有捕获
ArrayIndexOutOfBoundsException
。但是,如果我将catch子句改为catch
Exception
,它将按预期工作

超类异常是否应该捕获子类异常,即使它是
运行时异常

以下是异常的原因:

int timeInMillis = 0;

    for (int i = 0; i < commandMessage.length; i++)
        for (String commandValue : command.getArguments()) {
            try {
                if (commandValue.equals(commandMessage[i]))

                    // This is causing it.
                    timeInMillis =
                        Integer.parseInt(commandMessage[i + 1]);
                    else
                        throw new CommandSyntaxException(Problems.
                                SYNTAX_ERROR.getProblemDescription());
                } catch (CommandSyntaxException commandSyntaxException) {
                    System.out.println("foo");
                }

            }
除了捕获
异常
)之外,是否还有其他解决方法我的意图是在单个catch子句中捕获所有异常和我自己的异常。

添加

catch (ArrayIndexOutOfBoundsException e) {

}
为了让你明白这些话

ArrayIndexOutOfBoundException
CommandSyntaxException
是不同的异常,如果您想捕获它们,您应该分别捕获每个异常,或者捕获作为它们共同祖先的异常(
exception

更新 如果您现在想在1 catch子句中捕获,您可以

  • 等待Java7
  • 使您的CommandSyntax继承ArrayIndexOutOfBounds

  • 当您扩展异常并创建CommandSyntaxException时,它将成为一个特定的异常。现在您正试图捕获CommandSyntaxException,但该异常不会被抛出,而是ArrayIndexOutOfBound是线程,所以它不会被捕获。 如果您的代码抛出CommandSyntaxException,则只会捕获它。:)

    这个问题的快速解决方法有三种。 CommandSyntaxException扩展RuntimeException 或CommandSyntaxException扩展ArrayIndexOutOfBoundException。 或者您的代码抛出CommandSyntaxException

    “我的意图是在单个catch子句中捕获所有异常和我自己的异常”: 您可以使用Catch(Exception e)对所有异常进行分类,但使用单个Catch子句对所有异常进行分类并不是一种好的做法

    catch (ArrayIndexOutOfBoundsException e) {
    
    }