2010-09-19 90 views
8

我一直在研究这个程序很长一段时间,我的大脑被炸了。我可以使用一些帮助从一个人在看。为什么我的程序中“必须被捕获或被宣布为抛出”?

我试图做一个程序,逐行读取文本文件,每行都被制作为ArrayList,所以我可以访问每个令牌。我究竟做错了什么?

import java.util.*; 
import java.util.ArrayList; 
import java.io.*; 
import java.rmi.server.UID; 
import java.util.concurrent.atomic.AtomicInteger; 

public class PCB { 
    public void read (String [] args) { 
     BufferedReader inputStream = null; 

     try { 
      inputStream = new BufferedReader(new FileReader("processes1.txt")); 

      String l; 
      while ((l = inputStream.readLine()) != null) { 
       write(l); 
      } 
     } 
     finally { 
      if (inputStream != null) { 
       inputStream.close(); 
      } 
     } 
    } 

    public void write(String table) { 
     char status; 
     String name; 
     int priority; 

     ArrayList<String> tokens = new ArrayList<String>(); 

     Scanner tokenize = new Scanner(table); 
     while (tokenize.hasNext()) { 
      tokens.add(tokenize.next()); 
     } 

     status = 'n'; 
     name = tokens.get(0); 
     String priString = tokens.get(1); 
     priority = Integer.parseInt(priString); 

     AtomicInteger count = new AtomicInteger(0); 
     count.incrementAndGet(); 
     int pid = count.get(); 

     System.out.println("PID: " + pid); 
    } 
} 

我正要戳出我的眼球。我得到了三个错误:

U:\Senior Year\CS451- Operating Systems\Project1 PCB\PCB.java:24: unreported exception java.io.IOException; must be caught or declared to be thrown 
      inputStream.close();} 
          ^
U:\Senior Year\CS451- Operating Systems\Project1 PCB\PCB.java:15: unreported exception java.io.FileNotFoundException; must be caught or declared to be thrown 
     inputStream = new BufferedReader(new FileReader("processes1.txt")); 
             ^
U:\Senior Year\CS451- Operating Systems\Project1 PCB\PCB.java:18: unreported exception java.io.IOException; must be caught or declared to be thrown 
     while ((l = inputStream.readLine()) != null) { 
             ^

我在做什么错?

回答

13

当您在Java中使用I/O时,大多数情况下必须处理IOException,这可能会在读/写或关闭流时发生。

你必须把你的敏感块放在try // catch块中,并在这里处理异常。

例如:

try{ 
    // All your I/O operations 
} 
catch(IOException ioe){ 
    //Handle exception here, most of the time you will just log it. 
} 

资源:

+0

我该怎么做,虽然? – Luron 2010-09-19 19:36:56

+0

阅读示例的教程。 – camickr 2010-09-19 19:39:36

8

Java的编译时检查异常规范。您必须捕获异常或将其声明在方法签名中。这里是你如何声明它可能会从你的方法抛出:

public void read (String [] args) throws java.io.IOException { 

如果你的方法需要做一些回应,赶上例外。如果您的调用者需要了解失败,请将其声明为抛出。

这些不是相互排斥的。有时,捕捉异常,做某些事情并重新抛出异常或包装原始异常(“原因”)的新异常是非常有用的。

RuntimeException及其子类不需要声明。

0

良好的IDE会为您创建catch块或将该异常添加到方法声明中。

请注意,如果按照Colin的解决方案向方法声明中添加异常,则任何调用方法的方法也必须具有合适的catch块或在方法声明中声明异常。

-3

我有同样的问题。我解决了通过添加弹簧库“org.springframework.core”

相关问题