2013-10-22 238 views
-4

我需要在代碼中做什麼更改如果我刪除了「throws IOException」行?拋出的替代代碼拋出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'); 
    } 
} 
+1

捕獲異常。 –

+1

嘗試一下,然後回來。更多信息:[Lesson:Exceptions](http://docs.oracle.com/javase/tutorial/essential/exceptions/) –

+0

爲什麼拋出IOException? –

回答

2

您需要捕獲異常

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(); 
    } 
} 
+0

這段代碼的問題是你沒有關閉'BufferedReader'使用的資源。記得**總是**打電話'關閉'。 –

+0

@LuiggiMendoza你是對的! –

相關問題