2012-02-04 132 views
2
public class Employee { 


public static void main(String[] args) { 
    int j=3; 
    staples[] stemp = new staples[j]; 
    String file_name = "d:/personal/11636470/NetBeansProjects/Employee/src/employee/Xanadu.txt"; 

    throws IOException 

    { 

    Scanner s = null; 
    try { 
     s = new Scanner(
        new BufferedReader(
        new FileReader("file_name"))); 

     while (s.hasNext()) 
     { 
      System.out.println(s.next()); 
     } 
     } finally 
     { 
     if (s != null) 
      { 
      s.close(); 
      } 
     } 



try 

{ 

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

for (j=0;j<3;j++) 
     { 
      stemp[j] = new staples(); 

      System.out.print("Enter your name : "); 
      stemp[j].setName(reader.readLine()); 

      System.out.println("Enter your age : "); 
      stemp[j].setAge(Integer.parseInt(reader.readLine())); 


     } 


for (j=0;j<3;j++) 
     { 
      System.out.println("Employee number:" + j +" name:"+stemp[j].getName()+" Age:"+stemp[j].getAge()); 

     } 


reader.close(); // VERY IMPORTANT TO CLOSE 






System.out.println("Program ended"); 

} 

catch(java.io.IOException ex) 
{ 
    System.out.println("Error is " + ex.getMessage()); 
} 



} 

} }Java异常处理查询

这个问题似乎很简单,我得到在“抛出IOException异常”路线错误,是有什么错的try和catch方法,我实现?

该代码有两个部分,一个是读取文件xanadu.txt,另一个是复制获取员工数据。两者都尝试并捕获实现。

+2

有点重新格式化可能会有所帮助,我感到困惑的是第10行 – DaveRlz 2012-02-04 18:22:00

+0

是的,代码缩进遍布整个地方。 – 2012-02-04 18:22:56

+0

让我重新格式化它 – 2012-02-04 18:23:33

回答

1

这是你完全错误的部分。

try 
{ 
    s = new Scanner((Readable) new BufferedReader(new FileReader("file_name"))); 
    while (s.hasNext()) 
     System.out.println(s.next()); 
    } catch (IOException e) 
    { 
     // Do the error stuff. 
     e.printStackTrace(); 
    } finally 
    { 
     // Do it anyway. If error happens or not. 
     if (s != null) 
     s.close(); 
    } 
} 

throws IOException被放置在错误的地方,它应该放在这里:

public static void main(String[] args) throws IOException {

在这种情况下,你不需要任何尝试,catch块 - 你只不过是例外,传递给覆盖方法(在你的情况下你不需要担心它)让它处理抛出的异常,但是如果你想用try来处理异常,catch块你不需要这样。

1

throws子句在方法声明中有效,不在方法体内。

+0

所以你说抛出IOException应该放在其他地方? – 2012-02-04 18:27:36

+0

是的,它应该是'public static void main(String [] args)抛出IOException {'。主要方法可以声明为抛出异常。 – 2012-02-04 18:29:05

+0

或者您可以像Marcin所描述的那样在您的第一个尝试块中捕获该异常。 – 2012-02-04 18:31:19