【问题标题】:What does throws statement mean in java?java中的throws语句是什么意思?
【发布时间】:2012-09-21 02:57:33
【问题描述】:

另外,throws NumberFormatException, IOException 是什么意思?我一直试图通过说来使用BufferedReader

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

但除非输入throws NumberFormatException, IOException,否则BufferedReader 将不起作用。

【问题讨论】:

标签: java


【解决方案1】:

throws 关键字表示某个方法可以潜在地“抛出”某个异常。您需要使用 try-catch 块或在方法声明中添加 throws IOException, (...) 来处理可能的 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) {...} ... */
}

【讨论】:

  • IOException 是否需要在任何地方定义?如果它是一个对象,它必须有一个class 声明对吗?
【解决方案2】:

Throws 子句用于声明未由特定方法处理的异常,并指示调用者要么显式处理这些异常,要么在调用层次结构中重新抛出它们。

【讨论】:

    【解决方案3】:

    throws 语句意味着该函数可能会“抛出”错误。即吐出一个将结束当前方法的错误,并让堆栈上的下一个'try catch'块处理它。

    在这种情况下,您可以在方法声明中添加“throws....”,也可以这样做:

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

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

    【讨论】:

      猜你喜欢
      • 2011-04-28
      • 1970-01-01
      • 1970-01-01
      • 2011-11-18
      • 2011-08-15
      • 2012-05-07
      • 1970-01-01
      • 2023-03-12
      • 2014-04-13
      相关资源
      最近更新 更多