如何让我的程序返回 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;
}