26

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?

5
  • Post your code and LogCat. Commented Jun 25, 2014 at 19:36
  • 1
    Works fine for me. Post the stack trace. Commented Jun 25, 2014 at 19:38
  • And please put the code in your question, and not in comments. Commented Jun 25, 2014 at 19:42
  • 7
    Do you mean that the exception is actually being thrown? Or you simply mean Eclipse keeps telling you about the Exception? If it's the latter, it's because MalformedURLException is a checked exception, i.e., you must explicitly deal with it in code, either by wrapping it in a try/catch statement, or by adding throws MalformedURLException to the method stub. Commented Jun 25, 2014 at 19:47
  • is this line inside a try-catch block? Commented Jun 25, 2014 at 19:51

1 Answer 1

68

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Checked exceptions are not a bad idea. How they are being used in the case of MalformedURLException is. MalformedURLException should not be a checked exception, but the Java team made it so for some reason I am yet to understand.
unhandled exception means the exception needs to be handled
was using the new url in asynch doInBackground... only way i could get around the error. Thanks !

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.