Arya Arya - 4 months ago 11
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

SocketException
,
SSLException
,
SSLHandshakeException
or
ConnectException


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 = "";
try
{
if (i == 1)
throw new IOException();
else if (i == 2)
throw new SSLException("SSLEx");
else if (i == 3)
throw new SocketException();
else
text = "EVERYTHING GOOD";
}
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)
{
e.printStackTrace();
}

return text;
}


I call my test method by

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


Initially the program would catch a
SocketException
then retry by passing 1 so I can emulate a working proxy but a server response with
IOException
as
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

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.

Comments