2012-09-21 21 views
0

另外,throws NumberFormatException, IOException是什么意思?我一直试图通过说在java中抛出语句意味着什么?

BufferedReader nerd = new BufferedReader(new InputStreamReader(System.in)); 

BufferedReader除非throws NumberFormatException, IOException放在将无法正常工作使用BufferedReader

+0

您是否检查过文档? – SLaks

+0

谷歌“抛出java”。 –

+2

http://docs.oracle.com/javase/tutorial/essential/exceptions/throwing.html –

回答

3

throws子句用于声明不是由特定的方法来处理的异常,是一种指令给调用者明确地处理这些指令或者在调用层次结构中重新展开它们。

3

throws关键字表示某个方法可能会“抛出”某个异常。您需要处理可能的IOException(可能还有其他例外),或者使用try-catch块或将throws IOException, (...)添加到您的方法声明中。就像这样:

public void foo() throws IOException /* , AnotherException, ... */ { 
    BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); 
    in.readLine(); 
    // etc. 
    in.close(); 
} 


public void foo() { 
    BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); 
    try { 
     in.readLine(); 
     // etc. 
     in.close(); 
    } catch (IOException e) { 
     // handle the exception 
    } /* catch (AnotherException e1) {...} ... */ 
} 
1

throws语句表示该函数可能会“抛出”错误。即吐出一个错误,将结束当前的方法,并使堆栈中的下一个“try catch”块处理它。

在这种情况下,您可以添加“抛出....”的方法声明,或者你可以这样做:

try { 
    // code here 
} catch (Exception ex) { 
    // what to do on error here 
} 

阅读http://docs.oracle.com/javase/tutorial/essential/exceptions/获取更多信息。