作者热门文章
- iOS/Objective-C 元类和类别
- objective-c - -1001 错误,当 NSURLSession 通过 httpproxy 和/etc/hosts
- java - 使用网络类获取 url 地址
- ios - 推送通知中不播放声音
我已经为这个程序工作了很长一段时间,我的大脑被炸了。我需要一些正在查看的人的帮助。
我正在尝试制作一个逐行读取文本文件的程序,并将每一行制作成一个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) {
^
我做错了什么?
最佳答案
当您在 Java 中使用 I/O 时,大多数时候您必须处理 IOException,它可能在您读/写甚至关闭流时随时发生。
您必须将敏感 block 放在 try//catch block 中并在此处处理异常。
例如:
try{
// All your I/O operations
}
catch(IOException ioe){
//Handle exception here, most of the time you will just log it.
}
资源:
关于java - 为什么我的程序会出现 "must be caught or declared to be thrown"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3747155/
我是一名优秀的程序员,十分优秀!