gpt4 book ai didi

java - 创建 URL 时出现未报告的异常 MalformedURLException

转载 作者:搜寻专家 更新时间:2023-10-30 21:17:00 25 4
gpt4 key购买 nike

请原谅我缺乏 Java 技能,但我通常是 C 类人。我正在开始一些 Android 开发,我想简单地发出一个 GET 请求。但是,我什至不能得到一个简单的 URL 类型来正确编译。我不断收到此错误:

HelloWorld.java:17: error: unreported exception MalformedURLException; must be caught or declared to be thrown
URL url = new URL("http://www.google.com/");
^
1 error

运行这段简单的代码时:

 import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.Writer;
import java.net.HttpURLConnection;
import java.net.ProtocolException;
import java.net.URL;
import java.net.URLConnection;

public class HelloWorld{

public static void main(String []args){
URL url = new URL("http://www.google.com/");

System.out.println(url.toString());
}
}

我在这里做错了什么?

最佳答案

对于所有已检查的异常,必须在您的代码中处理它们。这里有 2 种方法可以做到这一点。

一般来说,您可以使用 throws 子句将异常处理传递给声明方法的调用者。或者您可以使用 try-catch[-finally] 结构自行处理它们。

在你的情况下,您要么需要将 throws 子句添加到 main() 方法中作为

public static void main(String []args) 抛出 MalformedURLException{

或者您需要用 try-catch block 包围 URL 声明,如下所示:

try{
URL url = new URL("http://www.google.com/");
//more code goes here
}catch(MalformedURLException ex){
//do exception handling here
}

关于java - 创建 URL 时出现未报告的异常 MalformedURLException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17733158/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com