2016-06-07 75 views
2

我想實現自己的異常來處理用戶是否正在查找不存在的數組中的值或訪問數組中未定義的索引。ArrayIndexOutOfBoundsException的用戶定義異常

int[] myIntArray = {1,2,3}; 
myIntArray[4] = ?? // this invoke ArrayIndexOutOfBoundsException 

所以我真正想要做的是這樣的:

try{ 
    System.out.println("Access element:" + a[4]); 
    }catch(ArrayIndexOutOfBoundsException e){ 
    // call my own exception witch I create in a new class 
    } 

一些如何這樣的:

public class myException extends Exception 
{ 
    public invalideIndexException() 
    { 

    } 
} 

我新的編程,Java的文檔是有幫助的,但是我仍然爲此而感到困惑。

+0

你可以做'拋出新MyException()之後;'了'catch' – pzaenger

回答

2

你應該嘗試

try{ 
    System.out.println("Access element:" + a[4]); 
    }catch(ArrayIndexOutOfBoundsException e){ 
    throw new CustomArrayIndexOutOfBoundException("blah blah"); // here 
    } 

拋出自己的異常捕獲ArrayIndexOutOfBoundsException

class CustomArrayIndexOutOfBoundException extends Exception{ 
CustomArrayIndexOutOfBoundException(String s){ 
    super(s); 
} 
} 
+0

內是否有可能寫CustomArrayIndexOutOfBoundException(「-------」); –

+1

@Cyber​​Allien是的。您可以。稍微更新了我的文章。 –

+0

最後一個問題,是否有可能在CustomArrayIndexOutOfBoundException類中放置多個異常來處理例如用戶正在查找的元素不存在和無效索引的異常。 –

相關問題