java - Unreported exception IOException reading file from URL -
i've looked on , have yet find solution this. long , short of i'm trying take text file provided url , read string can other things it.
the specific compile error is:
/tmp/java_kwweo5/main.java:49: error: unreported exception ioexception; must caught or declared thrown string text = readurltextcontent("http://textfiles.com/stories/antcrick.txt"); ^ 1 error
the code causing error, in 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); } { reader.close(); } } public static void main(string[] args) { string text = readurltextcontent("http://textfiles.com/stories/antcrick.txt"); system.out.println(text); } }
what modify short program compiles , executes?
while handle these exceptions in body of method wrapping them runtimeexception, method signature "lies" compiler:
private static string readurltextcontent(string url) throws ioexception, malformedurlexception {
change line to:
private static string readurltextcontent(string url) {
that should resolve compiler message
the problem you're experiencing here inherent checked exceptions. when method declares throws exception-type, compiler required check these exceptions handled.
this means, though correctly catch exceptions in method body, compiler must assume, these exceptions can happen.
accordingly whenever reaadurltextcontent
called, compiler checks "does caller handle these exceptions?"
if caller doesn't... that's :)
what makes case little more interesting malformedurlexception
subclass of ioexception
. means whenever catch (or throw) ioexception, malformedurlexception handled in same way, given has not been caught.
Comments
Post a Comment