I am connecting to a website using Jsoup. I have inserted a .timeout
to check if the website times out.
Because I already handle IOException
, my IDE is not allowing me to put another catch for SocketTimeOutException
, which is fair, I guess.
Is there a way to tell from IOException
what is the error? I'd like to have specific debugging output for different errors, so that I can keep the code clean and efficient.
Here is my code (yes, some variables are missing, they are pretty simple though and not really necessary):
Document doc = null;
try
{
doc = Jsoup.connect(Url).proxy(proxy).userAgent(userAgent).timeout(10000).get();
}
catch (IOException e)
{
if (...)
{
if(specificThread.running == false) {
System.out.println("Thread got interrupted! Link visited -> "+ Url);
Thread.currentThread().interrupt();
}
try
{
System.out.println("Localhost detected! If this happens, you're stupid");
doc = Jsoup.connect(Url).userAgent(userAgent).get();
}
catch (IOException e1)
{
System.out.println("Couldn't connect to " + Url + " , localhost was detected.");
e1.printStackTrace();
System.exit(-1);
}
catch (java.lang.IllegalArgumentException error)
{
System.out.println("Malformed URL detected -> " + Url) ;
}
}
else
{
System.out.println("Couldn't connect to " + Url);
e.printStackTrace();
}
}
catch (java.lang.IllegalArgumentException error)
{
System.out.println("Malformed URL detected -> " + Url);
}
catch (java.net.SocketTimeoutException error) //IDE Is blocking this
{
//Handle error here
}
Is it possible to do this?
Put the catch for the SocketTimeoutException
before the catch for the IOException
.
Exception handling works by looking through a table until a matching exception type is found. As such, more specific exceptions have to come before more general exceptions, in order that they can be matched.
This is described in JLS Sec 14.21, "Unreachable Statements":
It is a compile-time error if a statement cannot be executed because it is unreachable.
...
A catch block
C
is reachable iff both of the following are true:
- ...
- There is no earlier catch block A in the try statement such that the type of C's parameter is the same as or a subclass of the type of A's parameter.
So, you just need to make sure there is no earlier catch block catching a superclass parameter.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments