A question about exception catching in Java
I have an instance method, and within it, I did a simple webpage parsing:
public void doOperation(final AuthorAccess authorAccess, ArgumentsMap arguments) throws IllegalArgumentException,AuthorOperationException
{
final String server = "chiexist1.worldbook.com";
final String port = "8080";
try {
docBuilder = docFactory.newDocumentBuilder();
doc = docBuilder.parse("http://" + server + ":" + port + "/exist/webdav/db/portfolio/config/products.xml");
...}
catch{}
}
Because currently I am hard-coding the server address in the string, there might be situations where the server name is not right, so in that case, I want it to automatically to change the server URL string to "localhost".
I think an if-else statement probably would work, but I am not very sure how to d开发者_StackOverflowetermine the boolean variable for detecting whether this parsing is failed or not. I also think of putting this in the catch statement, but what about other statements are also throwing exceptions?
I've also checked the API for DocumentBuilder, the parse() method always return a Document Type but not boolean. So I would be grateful if anyone could give me some suggestions here on how to detect the wronged URL and then change to parsing localhost instead, thanks in advance.
I think that here you can find an answer: Validating URL in Java
The following code should do what you like. Basically, in the catch
just build another doc from localhost.
final String server = "chiexist1.worldbook.com";
final String port = "8080";
docBuilder = docFactory.newDocumentBuilder();
doc = null;
try {
doc = docBuilder.parse("http://" + server + ":" + port + "/exist/webdav/db/portfolio/config/products.xml");
} catch{
try{
doc = docBuilder.parse("http://" + "localhost" + ":" + port + "/exist/webdav/db/portfolio/config/products.xml");
} catch {
// now we have an error we can't recover from
}
}
... // I meant to do this before.
A general tip: don't just write "catch". Always specify which types of exceptions you're catching (preferably your own custom exception types), so that you know the code does exactly what you mean it to do. Otherwise, as you said, the catch statement may catch some other type of exception you didn't mean to occur, that should actually be thrown upwards.
You should catch the respective exceptions separately and perform different error handling logic depending on which exception you catch. That is considered the best approach since it separates error condiions from normal logic and u can have different errors handled differently.
It is considered better than if else statements within your normal flow of logic.
Keep track of the number of attempts in a variable and loop until success or max attempts (I chose 5) is passed:
String server = "chiexist1.worldbook.com";
final String port = "8080";
int attempts = 0;
final int MAX_ATTEMPTS = 5;
boolean success = false;
docBuilder = docFactory.newDocumentBuilder();
while (!success && attempts < MAX_ATTEMPTS) {
try {
doc = docBuilder.parse("http://" + server + ":" + port + "/exist/webdav/db/portfolio/config/products.xml");
success = true;
} catch (IOException e) {
if (++attempts < MAX_ATTEMPTS) {
System.err.println("Attempt to connect to " + server + ":" + port + " failed. Retrying" + (attempts == 1 ? ", but connecting to localhost:" + port + " this time" : "") + ".");
server = "localhost";
} else {
System.err.println("Attempt to connect to " + server + ":" + port + " failed. Giving up after " + attempts + " failed attempts.");
}
}
}
if (!success) {
// Tidy up and exit
}
// Do stuff
Try something like this:
static String hostname = "hostname";
static{
if(doesHostExist(hostName)==false){
hostname="localhost";
}
}
private static boolean doesHostExist(String host){
try {
URL url = new URL("http://" + host);
URLConnection conn = url.openConnection();
conn.connect();
return true;
} catch (MalformedURLException e) {
return false;
} catch (IOException e) {
return false;
}
}
*edit additional code lifted from a previous answer: Validating URL in Java
精彩评论