Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
371 views
in Technique[技术] by (71.8m points)

android - Java Malformed URL Exception

I'm trying to make an http POST request in an android app I'm building, but no matter what url I use for the request, Eclipse keeps raising a Malformed URL Exception. I've tried a line of code from one of the android tutorials:

URL url = new URL("https://wikipedia.org");

And even that triggers the error. Is there a reason Eclipse keeps raising this error for any URL I try to create?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It is not raising the exception, it's complaining that you haven't handled the possibility that it might, even though it won't, because the URL in this case is not malformed. (Java's designers thought this concept, "checked exceptions", was a good idea, although in practice it hasn't worked well.)

To shut it up, add throws MalformedURLException, or its superclass throws IOException, to the method declaration. For example:

public void myMethod() throws IOException {
    URL url = new URL("https://wikipedia.org/");
    ...
}

Alternatively, catch and rethrow the annoying exception as an unchecked exception:

public void myMethod() {
    try {
        URL url = new URL("https://wikipedia.org/");
        ...
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

Java 8 added the UncheckedIOException class for rethrowing IOExceptions when you cannot otherwise handle them. In earlier Java versions, use RuntimeException.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...