【问题标题】:getting input in java throws exception在java中获取输入抛出异常
【发布时间】:2013-09-11 16:31:35
【问题描述】:
DataInput in = new DataInputStream(System.in);
System.out.println("What is your name");
String name = in.readLine();

错误提示“未处理的 IO 异常”。这段代码有什么问题?

【问题讨论】:

  • readLine 抛出检查异常
  • @WinCoder 我快速解释了已检查和未检查的异常here

标签: java


【解决方案1】:

未处理的 IO 异常

要么 catch IOException 要么声明它抛出,readLine() 声明它可以抛出这个异常,所以你的代码需要处理/抛出它

【讨论】:

    【解决方案2】:

    您必须用try/catch 包围对in.readLine () 的调用。

    DataInput in = new DataInputStream(System.in);
    System.out.println("What is your name");
    
    try {
        String name = in.readLine();
    } catch (IOException ioex) {
        // Handle exception accordingly
    }
    

    或者您可以在方法签名中添加trows IOException 子句,这意味着调用方法必须处理异常(使用try/catch 块)。

    根据Javadoc entryreadLine () 方法已被弃用,您应该改用BufferedReader

    【讨论】:

    • 为什么控制台交互方法会抛出异常?
    • @WinCoder 如果在读取流时发生 I/O 错误,将抛出 IOException,并在异常对象中提供可用的详细信息。
    • 可能有多种原因。最终,这并不重要,因为该方法被声明为throws IOException,您需要以一种或另一种方式来处理异常,无论是通过捕获它还是通过声明您的方法throws IOException(或某个超类IOException)
    【解决方案3】:

    readLine() 抛出 IOException 被检查的异常应该在编译时抛出或处理参见Oracle documentation

    【讨论】:

      【解决方案4】:

      这个方法readLine() 抛出IOException 这是一个检查异常。因此,您有两个选项可以捕获并处理它和/或在方法声明中添加 throws 关键字

      例子:

      public void throwsMethod() throws IOException{
        DataInput in = new DataInputStream(System.in);
        System.out.println("What is your name");
        String name = in.readLine();
        .
        .
      }
      
      public void handleMethod(){
        DataInput in = new DataInputStream(System.in);
        System.out.println("What is your name");
        String name=null;
        try{
          name = in.readLine();
        }catch(IOException){
         //do something here
        }
        .
        .
      }
      

      更多信息请阅读这篇oracle文章Exceptions

      【讨论】:

        猜你喜欢
        • 2013-09-10
        • 1970-01-01
        • 1970-01-01
        • 2016-08-10
        • 2015-06-24
        • 1970-01-01
        • 2012-07-23
        • 1970-01-01
        相关资源
        最近更新 更多