gpt4 book ai didi

java - 为什么我的程序会出现 "must be caught or declared to be thrown"?

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:09:07 24 4
gpt4 key购买 nike

我已经为这个程序工作了很长一段时间,我的大脑被炸了。我需要一些正在查看的人的帮助。

我正在尝试制作一个逐行读取文本文件的程序,并将每一行制作成一个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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com