【问题标题】:Alternate code for Throws IOException [closed]引发 IOException 的替代代码 [关闭]
【发布时间】:2013-10-22 14:16:40
【问题描述】:

如果我删除“throws IOException”行,我需要对代码进行哪些更改??

import java.io.*;
class Buffered_class{
    public static void main(String[] args) 
                    throws IOException // remove this line 
    {
        char c;
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        System.out.print("Enter characters, 'q' to quit");
        do{
           c= (char)br.read();
           System.out.println(" you entered : " + c );
       }while(c !='q'); 
    }
}   

【问题讨论】:

  • 尝试一下,然后回来。更多信息:Lesson: Exceptions
  • 你为什么抛出 IOException ?
  • @AbdullahShaikh 使用 BufferedReader#read 抛出 IOException
  • @LuiggiMendoza 我知道。我希望 OP 回答/知道,然后理解为什么要抓住它。 :)
  • @AbdullahShaikh 有很多资源,还有关于异常处理的官方资源。我们只能希望 OP 自己学习一些东西。

标签: java exception exception-handling ioexception


【解决方案1】:

你需要捕捉异常

import java.io.*;    
class Buffered_class{
    public static void main(String[] args)
    {
       char c;
       try{
           BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
           System.out.print("Enter characters, 'q' to quit");        
           do{
               c= (char)br.read();
               System.out.println(" you entered : " + c );

           }while(c !='q'); 
       }catch(IOException e){
             // do something
       }finally{
           br.close();
   }
}

【讨论】:

  • 这段代码的问题是你没有关闭BufferedReader使用的资源。请记住始终致电close
  • @LuiggiMendoza 你是对的!
猜你喜欢
  • 1970-01-01
  • 2011-12-08
  • 1970-01-01
  • 2011-09-24
  • 2011-04-10
  • 1970-01-01
  • 2020-10-16
  • 2010-09-22
  • 1970-01-01
相关资源
最近更新 更多