Java 格式错误的 URL 异常

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24416930/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 12:05:25  来源:igfitidea点击:

Java Malformed URL Exception

javaandroidmalformedurlexception

提问by user3772689

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:

我正在尝试在我正在构建的 android 应用程序中发出 http POST 请求,但无论我用于请求的 url 是什么,Eclipse 都会不断引发格式错误的 URL 异常。我已经尝试了其中一个 android 教程中的一行代码:

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?

甚至会触发错误。对于我尝试创建的任何 URL,Eclipse 是否有原因不断引发此错误?

采纳答案by Boann

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.)

它不是引发异常,而是抱怨您没有处理它可能的可能性,即使它不会,因为在这种情况下的 URL 没有格式错误。(Java 的设计者认为“检查异常”这个概念是一个好主意,尽管在实践中效果不佳。

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

要关闭它,请将throws MalformedURLException或其超类添加throws IOException到方法声明中。例如:

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 UncheckedIOExceptionclass for rethrowing IOExceptions when you cannot otherwise handle them. In earlier Java versions, use RuntimeException.

Java 8 添加了UncheckedIOException用于IOException在您无法以其他方式处理它们时重新抛出s的类。在早期的 Java 版本中,使用RuntimeException.