Arya Arya - 1 year ago 66
Java Question

retry on some exceptions recursive

I have a method which uses proxies to retrieve information from a server. Sometimes due to a bad proxy I get


I want the method to retry on the exceptions above, but on the IOException or no exception I want a string returned

Here is the method I constructed to test different scenarios

public String getTest(int i, int current, int total)
String text = "";
if (i == 1)
throw new IOException();
else if (i == 2)
throw new SSLException("SSLEx");
else if (i == 3)
throw new SocketException();
catch (SSLException | SocketException re)
if (current < total)
System.out.println("Recalling " + current);
getTest(1, ++current, total);
catch (IOException ioe)
text = "HTTP ERROR";
catch (Exception e)

return text;

I call my test method by

System.out.println(c.getTest(3, 0, 5));

Initially the program would catch a
then retry by passing 1 so I can emulate a working proxy but a server response with
i = 1
but the method never returns the text "HTTP ERROR"

What do I need to change in order for this to work as expected?

Answer Source

In order to return the string returned by your recursive function call, you must place return before the recursive function call like so...

return getTest(1, ++current, total);

Right now you are simply running the recursive function and discarding its return value. Your logic then returns your text string from the initial call (which in the case of an SSLException looks like an empty string).

You could also accomplish the same effect by assigning text from the recursive function...

text = getTest(1, ++current, total);

Both statements, considering the rest of your logic, are equivalent.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download