2011-05-23 87 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