Java Malformed URL Exception

て烟熏妆下的殇ゞ 提交于 2019-11-28 11:54:25

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!