2012-11-13 68 views
1

很坦白地說,我只是不理解我的老師在這裏要求我做什麼。我嘗試使用「try-catch」塊,並在方法簽名中引發Exception。我讀過關於已檢查和未檢查的異常。我敢肯定,這將被拒絕或關閉,但有人可以在這裏投擲一塊骨頭嗎?我的教官的指示如下:爲什麼不能編譯下面的java代碼?

「改正它編譯。」

class Exception3{ 
    public static void main(String[] args){   
    if (Integer.parseInt(args[0]) == 0)    
     throw new Exception("Invalid Command Line Argument");  
    } 
} 

很明顯,它拋出了一個RuntimeException。更具體地說是一個ArrayIndexOutOfBoundsException。我知道異常的原因是因爲數組是空的,所以引用的索引不存在。我的意思是,從技術上講,我可以刪除if(Integer.parseInt(args[0]) == 0)throw new Exception("Invalid Command Line Argument");並將其替換爲System.out.println("It compiles now");

任何想法?

回答

7
public static void main(String[] args) throws Exception{   
    if (Integer.parseInt(args[0]) == 0)    
     throw new Exception("Invalid Command Line Argument");  
    } 

你的方法拋出Exception,所以方法聲明應當具體規定,則可能會Exception

作爲每java tutorial

經過例外都受到了捕捉或指定要求。除了由Error,RuntimeException及其子類指示的異常外,所有異常均爲檢查異常。

+0

就這樣?我只需要這麼做? – Lambda

+0

應該是這樣。你的代碼應該編譯。 – kosa

+0

LMAO!那是我2小時前做的第一件事!我非常沮喪的原因,並決定來這裏,是因爲當我跑這個該死的東西時我得到了這個。線程「main」中的異常java.lang.ArrayIndexOutOfBoundsException:0 – Lambda

3

你必須使用try catch語句要麼抓住它:

class Exception3 { 
    public static void main(String[] args) { 
     try { 
      if (Integer.parseInt(args[0]) == 0) 
       throw new Exception("Invalid Command Line Argument"); 
     } 
     catch (Exception e) { 
      e.printStackTrace(); 
     } 
    } 
} 

,或者在方法頭聲明它:

class Exception3 { 
    public static void main(String[] args) throws Exception { 
     if (Integer.parseInt(args[0]) == 0) 
      throw new Exception("Invalid Command Line Argument"); 
    } 
} 
+0

並感謝您的意見。 – Lambda