how to avoid Infinite Recursion in a non-return method with Try catch

51 Views Asked by At

public class Sample {

public static void main(String[] args) {

    method();

}

public static void method()
{
    try {
        System.out.println("function");
        throw new StaleElementReferenceException("thih sexception occured");
    }
    catch (StaleElementReferenceException e) {
        method();
    }
    catch (Exception e) {
        System.out.println("AssertFail");
    }
}

}

how to avoid Infinite Recursion in a non-return method with Try catch...For Example this code below...when the StaleElementException Occurs only once i want to execute "functions after Exception , if the Stale Element occurs the second time i want it to go to Exception catch and print Assert fail..how?

2

There are 2 best solutions below

2
On
public class Sample {

public static void main(String[] args) {

    method(false);

}

public static void method(boolean calledFromCatchBlock)
{
    try {
        System.out.println("function");
        if(!calledFromCatchBlock) {
            throw new StaleElementReferenceException("thih sexception occured");
        } else {
            throw new Exception();
        }
    } catch (StaleElementReferenceException e) {
        method(true);
    } catch (Exception e) {
        System.out.println("AssertFail");
    }
}
}
3
On

You should store somehow the state when you throw an exception (e.g. a boolean flag) outside method(), check this state and throw modified exception next time:

private static boolean alreadyThrown = false;

public static void method()
{
    try {
        System.out.println("function");
        if (alreadyThrown) {
            throw new RuntimeException("another exception occured");
        } else {
            alreadyThrown = true;
            throw new StaleElementReferenceException("this exception occured");
        }
    }
    catch (StaleElementReferenceException e) {
        method();
    }
    catch (Exception e) {
        System.out.println("AssertFail");
    }
}

Or you could provide some argument to the method(int arg) and check its value in a similar way:

public static void main(String[] args) {
    method(1);
}

public static void method(int arg)
{
    try {
        System.out.println("function");
        if (arg > 1) {
            throw new RuntimeException("another exception occured");
        } else {
            throw new StaleElementReferenceException("this exception occured");
        }
    }
    catch (StaleElementReferenceException e) {
        method(arg + 1);
    }
    catch (Exception e) {
        System.out.println("AssertFail");
    }
}