2013-02-26 68 views
0
try { 
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 
    str = br.readLine(); 
    i = Integer.parseInt(str); 
} catch(NumberFormatException e) { 
    System.out.Println("enter a valid input"); 
} 

當我嘗試編譯這段代碼時,它會拋出一個編譯錯誤,說明ioexception正在發生,我應該趕上它。爲什麼在numberformatexception發生時聲明ioexception?

因此,我必須添加catch(IOException e)語句,但發生的異常是java.lang庫的數字格式異常,爲什麼我必須趕上ioException

回答

5
str=br.readLine(); 

BufferedReader.readLine()拋出IOException異常

public String readLine() throws IOException 

拋出:IOException - 如果發生I/O錯誤

IOException異常是checked異常,你要麼需要使用try/catch塊來處理它,或者使用拋出聲明它條款。

try 
{ 
BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 
str=br.readLine(); 
i=Integer.parseInt(str); 
}catch(IOException e) 
{System.out.println("IOException occured... " + e.printStacktrace()); 
catch(NumberFormatException e) 
{System.out.println("enter a valid input"); 
} 

Java 7中多重catch:

try 
    { 
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 
    str=br.readLine(); 
    i=Integer.parseInt(str); 
    } 
catch(IOException | NumberFormatException ex) { 
System.out.println(ex.printStackTrace()) 
} 
+0

所以程序甚至應該工作,如果我只IOException異常處理,但如果我這樣做,那麼當我不是一個整數 – shankisam912 2013-02-26 13:27:47

+0

@ shankisam912進入NumberFormatException的任何其他程序引發運行時錯誤是一個未經檢查的運行時異常。編譯器不會強制你處理RunTimeException。 IOException是一個選中的異常。即,如果一段代碼容易引發未經檢查,Exception編譯器將強制您處理它。 – PermGenError 2013-02-26 13:29:32

+0

我也將不得不做同樣的事情,如果我去br.read(); – shankisam912 2013-02-26 13:34:44

0

beacuse this line str = br.readLine();可以是發生IOException的

+1

比從來沒有更好的遲到,amiright? – 2013-02-26 13:25:17

+0

是的,多彩的比喻:) – Gospel 2013-02-26 13:30:05

0

這是因爲,

bufferedReader.readLine() 

拋出IOException異常這是一個檢查的異常。所有檢查的異常應該在try catch塊中。您可以捕獲IOException或一般異常。代碼片段如下。 NumberFormatException也是一個運行時異常。除非需要它,否則不需要捕獲它。

try { 
    String str = bufferedReader.readLine(); 
} catch (IOException ie) { 
    ie.printStacktrace(); 
} 


try { 
    String str = bufferedReader.readLine(); 
} catch (Exception ie) { 
    e.printStacktrace(); 
} 
相關問題