简体   繁体   中英

Why is UnknownHostException not caught in Exception (java)?

My code looks like this :

try
{
   String htmlPageText=readFromHtml("http://www.yahoo.com");
}
catch (Exception e)
{
  System.out.println("===Here===");
}

Method readFromHtml() will take a URL and return an HTML page. Normally it works fine. But I'm trying to simulate a "site down" situation, so I unplugged the Internet connection. I thought, the error should be caught and the result will be "===Here===", but instead, it returned:

java.net.UnknownHostException: http://www.yahoo.com"

and never printed out "===Here===". UnknownHostException is an extension of java.lang.Exception , so why was it not caught in the catch clause? Do I need a catch (UnknownHostException ex) to get it?

What is the readFromHTML method source code ? My guess is that this method throws some kind of exception but not UnknownHostException... Somewhere else in your code the exception is left unhandled.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM