BugHunterUK BugHunterUK - 1 year ago 213
Java Question

Java, MalformedURLException

I'm using

java.net.URL
, but I'm receiving a
MalformedURLException
. I've tried looking through the documentation, but I can't see what I'm doing wrong.

Below is a sample of my code that is fired when a button is pressed.

public class DownloadController {
public void downloadResource() {
URL obj = new URL("http://www.example.com/docs/resource1.html");
}
}


What am I doing wrong? I am using IntelliJ. There is no more code to show, the above code is literally the controller. I've only just started working on it.

Answer Source

The URL is fine. You're not receiving a MalformedURLException; you're getting a compile-time error about not handling one if one were thrown. It won't happen with the given URL, but the compiler doesn't know that.

You need to either add a try/catch clause:

public void downloadResource() {
    try {
        URL obj = new URL("http://www.example.com/docs/resource1.html");
    }
    catch (MalformedURLException exception) {
        // You could re-throw the exception as a runtime exception which doesn't
        // need to be caught.
        throw new RuntimeException(exception);
    } 
}

or add a throws clause:

public void downloadResource() throws MalformedURLException {
    URL obj = new URL("http://www.example.com/docs/resource1.html");
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download