2011-05-23 102 views
-1

我有一个自定义例外延伸Exception,但它似乎并没有赶上ArrayIndexOutOfBoundsException。但是,如果我改变捕捉条款来捕捉Exception,它会按预期工作。ArrayIndexOutOfBoundsException的自定义异常

不应该超类异常捕获子类异常,即使它是RuntimeException

这里是例外的原因:

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"); 
       } 

      } 

​​和commandValue是枚举。
这里是我的异常类:

public class CommandSyntaxException extends Exception { 
    private String message; 

    public CommandSyntaxException(String message) { 
     this.message = message; 
    } 

    @Override 
    public String getMessage() { 
     return message; 
    } 
} 

有任何解决方法(除了醒目Exception)? 我的意图是在单个catch子句中用我自己的异常捕获所有异常。

+0

Downvoted?请解释! – whirlwin 2011-05-23 10:20:07

回答

2

您CommandSyntax继任者当你扩展异常和创建CommandSyntaxException它成为一个特定的异常。现在你正在尝试捕获CommandSyntaxException,但是不会抛出异常,而是ArrayIndexOutOfBound是线程,所以它不会被捕获。 如果你的代码抛出CommandSyntaxException,那么只有它会被捕获。 :)

快速解决此问题可以有三种方法。 CommandSyntaxException扩展RuntimeException 或CommandSyntaxException扩展ArrayIndexOutOfBoundException。 或者您的代码引发CommandSyntaxException。我的意图是在单个catch子句中捕捉所有异常,并使用我自己的异常“: 您可以使用Catch捕获所有异常(异常e)但是使用单个catch子句捕获所有异常并不是一个好习惯。

1

添加

catch (ArrayIndexOutOfBoundsException e) { 

} 

你catch语句。

ArrayIndexOutOfBoundExceptionCommandSyntaxException是不同的例外,如果你想要捕捉它们,你应该单独捕获每个异常或捕获它们的共同祖先(Exception)的异常。

更新 如果现在要在1个catch子句抓住你可以

  1. 等待Java 7的http://www.baptiste-wicht.com/2010/05/better-exception-handling-in-java-7-multicatch-and-final-rethrow/
  2. 制作的ArrayIndexOutOfBounds