我看了很多,还没有找到解决方案。它的长短是我试图从提供的URL中获取文本文件并将其读入字符串,以便我可以使用它做其他事情。
具体的编译错误是:
/tmp/java_kWWEO5/Main.java:49: error: unreported exception IOException; must be caught or declared to be thrown String text = readUrlTextContent("http://textfiles.com/stories/antcrick.txt"); ^ 1 error
导致错误的代码,位于main
:
import java.util.*;
import java.net.URL;
import java.net.MalformedURLException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
public class Main {
private static String readUrlTextContent(String url) throws IOException, MalformedURLException {
URL source = new URL(url);
BufferedReader reader = new BufferedReader(new InputStreamReader(source.openStream()));
try {
StringBuilder builder = new StringBuilder();
String line = reader.readLine();
while (line != null) {
builder.append(line);
builder.append("\n");
line = reader.readLine();
}
return builder.toString();
} catch (MalformedURLException urlEx) {
urlEx.printStackTrace();
throw new RuntimeException("Malformed URL Exception", urlEx);
} catch (IOException ioEx) {
ioEx.printStackTrace();
throw new RuntimeException("IO Exception", ioEx);
} finally {
reader.close();
}
}
public static void main(String[] args) {
String text = readUrlTextContent("http://textfiles.com/stories/antcrick.txt");
System.out.println(text);
}
}
我该怎么做才能修改这个简短的程序,以便它最终编译并执行?
答案 0 :(得分:2)
当你通过将它们包装到RuntimeException中实际处理方法体中的这些异常时,你的方法签名“谎言”给编译器:
private static String readUrlTextContent(String url) throws IOException, MalformedURLException {
将此行更改为:
private static String readUrlTextContent(String url) {
那应解决编译器消息
您在此遇到的问题是检查异常所固有的问题。当一个方法声明它抛出某个异常类型时,编译器必需来检查这些异常是否被处理。
这意味着,即使您正确捕获了方法体中的异常,编译器也必须假定,这些异常可能会发生。
因此,无论何时调用reaadUrlTextContent
,编译器都会检查“调用者是否处理这些异常?”
如果来电者没有......那就是你得到的:)
使您的案例更有趣的是MalformedURLException
是IOException
的子类。这意味着无论何时捕获(或抛出)IOException,MalformedURLException都将以相同的方式处理,因为它尚未被捕获。
答案 1 :(得分:1)
更新readUrlTextContent(String url)的签名,如下所示:
private static String readUrlTextContent(String url) throws IOException{
}
并且,修改main()如下:
public static void main(String[] args) {
String text = null;
try {
text = readUrlTextContent("http://textfiles.com/stories/antcrick.txt");
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(text);
}
或者只修改readUrlTextContent(),如下所示:
private static String readUrlTextContent(String url) {
BufferedReader reader = null;
try {
URL source = new URL(url);
reader = new BufferedReader(new InputStreamReader(
source.openStream()));
StringBuilder builder = new StringBuilder();
String line = reader.readLine();
while (line != null) {
builder.append(line);
builder.append("\n");
line = reader.readLine();
}
return builder.toString();
} catch (MalformedURLException urlEx) {
urlEx.printStackTrace();
throw new RuntimeException("Malformed URL Exception", urlEx);
} catch (IOException ioEx) {
ioEx.printStackTrace();
throw new RuntimeException("IO Exception", ioEx);
} finally {
try {
if(null!=reader)
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}