为什么我的节目“必须被抓或被宣布被抛出”?

我已经在这个项目上工作了很长一段时间,而且我的大脑都被炒了。 我可以使用一些人的帮助。

我正在尝试创建一个逐行读取文本文件的程序,每行都被创建为一个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 tokens = new ArrayList(); 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) { ^ 

我究竟做错了什么?

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

您必须将敏感块放在try // catch块中并在此处理exception。

例如:

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

资源:

  • oracle.com – 课程:例外

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

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

如果您的方法需要做出响应,请捕获exception。 如果您的调用者需要知道失败,则将其声明为抛出。

这些不是相互排斥的。 有时捕获exception,执行某些操作并重新抛出exception或包装原始exception的新exception(“原因”)非常有用。

不需要声明RuntimeException及其子类。

好的IDE将为您创建catch块或将exception添加到方法声明中。

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

你宁愿这样做

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

一般来说,如果你需要非常具体的日志,那么在某个时候捕获类本身并将你的逻辑决定为catch或做一个instanceof并不是一个坏主意。

我曾经也有过一样的问题。 我通过添加弹簧库“org.springframework.core”解决了这个问题