问题
I have to download some URLs, and it can happen that during the operations some exception may occur, like java.net.NoRouteToHostException
. I consider it a temporary error exception, as the download can succeed if you retry it after some time.
So, I'd like to catch all those exceptions related to temporary errors, and I've started with these: java.net.NoRouteToHostException
, java.net.SocketException
Can you list other exceptions like these?
回答1:
java.net.SocketException
is the parent of java.net.NoRouteToHostException
so you could maybe catch only the parent. The others childs of SocketException
are BindException
, ConnectException
and PortUnreachableException
. Maybe it's ok to catch only SocketException
in your case...
回答2:
One pattern which is sometimes useful for dealing with transitory errors on retry-able operations is to define an error-callback interface and some classes that implement it; when an error occurs, let the callback object know, and let it decide whether an exception should be thrown or the action should be retried. Because the existing communications classes don't follow such a pattern, it may be necessary to catch their exceptions and turn them into callbacks.
Note that this approach allows much cleaner handling of many error-handling scenarios than would normal exception handling. Among other things, it makes it easy to set policies for how many retries may be attempted, how long they may take, etc. and also provides a means of skipping future retries if something like a "cancel" request is received.
回答3:
As @reef has already said java.net.NoRouteToHostException exntends java.net.SocketException, so if you catch java.net.SocketException it is enough. But java.net.SocketException extends IOException and I think that this is what you really should to catch. All IO problems should throw this exception.
回答4:
HttpRetryException is another. Maybe everything in java.net that does not extend SocketException?
One quick (and very dirty) way could be
try {
....
} catch(Exception e) {
if(e.getClass().getPackage().getName().equalsIgnoreCase("java.net")) {
retry();
}
}
来源:https://stackoverflow.com/questions/5106810/catching-exceptions-caused-by-temporary-network-errors