2013-11-25 155 views
0

enter image description here爲什麼會拋出InterruptedException?

這段代碼應該編譯,如果不是這樣?我究竟做錯了什麼?我希望代碼在顯示數組中的每個數字之前暫停一下。

public static void median(int odd[]) throws InterruptedException { 

    Arrays.sort(odd); 

    for (int i = 0; i < odd.length; i++) { 
     System.out.println(odd[i]); 
     Thread.sleep(500); 
    } 
    System.out.println("The median number of the previous list of numbers is: " + odd[5]); 
} 
+1

是的,它編譯。查看有關檢查到的異常的教程。那些必須被宣佈爲拋出或被捕。 –

+1

**是否拋出異常,或者是否擔心必須處理異常? – Makoto

+0

@Makoto我只想讓事情運行!它不會。我更新了netbeans給我的錯誤信息。 –

回答

0

使用TimerTimerTask而不是使線程睡眠。

0

我並不完全相信拋出異常,但是您必須聲明它被拋出或者自己捕獲它的原因歸結於它是checked exception

由於InterruptedException被聲明爲該方法的簽名的一部分,因此您需要以某種方式解決它。

2

我假設你main您有類似

public static void main (String[] args) { 
    int[] array = new int[X]; 
    ...// populate array 
    median(array); 
} 

因爲median是宣佈投擲檢查異常的方法,您必須趕上Exception或重新拋出。

public static void main (String[] args) { 
    int[] array = new int[X]; 
    ...// populate array 
    try { 
     median(array); 
    } catch (InterruptedException e) { 
     // handle it 
    } 
} 

public static void main (String[] args) throws InterruptedException { 
    int[] array = new int[X]; 
    ...// populate array 
    median(array); 
} 
1

這是更好地使用try catch塊爲Thread.sleep

取出拋出異常,改變

Thread.sleep(500); 

try{Thread.sleep(500);}catch(Exception e){} 
相關問題