【发布时间】:2019-03-24 12:49:41
【问题描述】:
如何让我的程序返回 MalformedUrlException 而不仅仅是一般的异常?
我正在制作一个简单的函数,它读取用户在控制台中输入的 URL,并从 URL 返回内容。我需要它来检查 URL 是有效的 URL 还是不是有效的 URL。
示例网址: http://google.com/not-found.html http://google.com
我创建了两个捕获异常,但似乎总是返回整体异常而不是 MalformedUrlException。
public static String getUrlContents(String theUrl) {
String content = "";
try {
URL url = new URL(theUrl);
//Create a url connection object
URLConnection urlConnection = url.openConnection();
//wrap the url connection a buffered reader
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
String line;
while((line = bufferedReader.readLine()) != null) {
content += line + "\n";
}
bufferedReader.close();
} catch (MalformedURLException e) {
System.out.println("The following url is invalid'" + theUrl + "'");
//logging error should go here
} catch (Exception e) {
System.out.println("Something went wrong, try agian");
}
return content;
}
【问题讨论】:
-
docs.oracle.com/javase/8/docs/api/java/net/…: 抛出:MalformedURLException - 如果未指定协议,或发现未知协议,或规范为空。
-
您能否提供一个带有不良行为的输入示例?
-
@tworogue 如果我输入 http:/google.com 或 google.com/not-found.html 我希望它抛出 MalformedURlException
-
@AhmeeyaGoldman 看看我的回答。
标签: java http exception get malformedurlexception