异常,而不是捕获Java MalformedURLException,生成失败
Java新手,请耐心听我说: (请注意,本qestion是关于Java异常的,而不是关于Jsoup)
当使用Jsoup获取Html页面时:(Jsoup.connect(当前url.\u名称)。get();),我试图根据Jsoup文档捕获所有可能的5个异常:here
该程序可以很好地处理好URL,但当我故意拼错1个URL来检查发生了什么时,我惊讶地发现异常没有被捕获,相反,程序开始运行,然后“构建失败”?
当只构建程序时没有失败,所以我认为它不是真正的
构建问题
代码如下:
// load html and check them:
for(URL current_url : URLs)
{
// no keyword - all getting 'yes'
if(keywords.isEmpty())
{
current_url._stat = URL_stat.YES;
}
// there are keywords - get pages and check them
else
{
Document html_doc;
// try to get document and catch all errors
try
{
html_doc = Jsoup.connect(current_url._name).get();
}
catch(MalformedURLException e)
{
System.out.println("the request " + current_url._name +
" URL is malformed");
System.out.println(e.getMessage());
current_url._stat = URL_stat.ERROR;
}
catch(HttpStatusException e)
{
System.out.println("page " + current_url._name + " response"
+ " is not ok");
System.out.println(e.getMessage());
current_url._stat = URL_stat.ERROR;
}
catch(UnsupportedMimeTypeException e)
{
System.out.println("page " + current_url._name+ " mime type"
+ " is not supported");
System.out.println(e.getMessage());
current_url._stat = URL_stat.ERROR;
}
catch(SocketTimeoutException e)
{
System.out.println("connection to " + current_url._name +
" times out");
System.out.println(e.getMessage());
current_url._stat = URL_stat.ERROR;
}
catch(IOException e)
{
System.out.println("an error occurred while getting page "
+ current_url._name);
System.out.println(e.getMessage());
current_url._stat = URL_stat.ERROR;
}
// check if document has paragraphs, if not mark - no
}
}
以及输出:
Exception in thread "main" java.lang.IllegalArgumentException: Malformed URL: ttp://cooking.nytimes.com/topics/what-to-cook-this-week
at org.jsoup.helper.HttpConnection.url(HttpConnection.java:76)
at org.jsoup.helper.HttpConnection.connect(HttpConnection.java:36)
at org.jsoup.Jsoup.connect(Jsoup.java:73)
at ex2.Ex2.main(Ex2.java:123)
Caused by: java.net.MalformedURLException: unknown protocol: ttp
at java.net.URL.<init>(URL.java:600)
at java.net.URL.<init>(URL.java:490)
at java.net.URL.<init>(URL.java:439)
at org.jsoup.helper.HttpConnection.url(HttpConnection.java:74)
... 3 more
C:\Users\Administrator\AppData\Local\NetBeans\Cache\8.2\executor- snippets\run.xml:53: Java returned: 1
BUILD FAILED (total time: 3 seconds)
谢谢
# 1 楼答案
这是因为引发的第一个异常是IllegalArgumentException,您尚未在任何catch子句中定义该异常,因此无法在任何其他catch块中获取自定义错误消息