How to break/exit different levels of method-calling in Java

Hamlyn picture Hamlyn · Apr 2, 2011 · Viewed 10.3k times · Source

Let's say I have:

public void one() {
  two();
  // continue here
}
public void two() {
  three();
}
public void three() {
  // exits two() and three() and continues back in one()
}

Are there any methods to doing this?

Answer

Peter Lawrey picture Peter Lawrey · Apr 2, 2011

The only way to do this without change method two() is to throw an Exception.

If you can change the code you can return a boolean which tells the caller to return.

However the simplest solution is to inline the methods into one larger method. If this is too large you should retsructure it another way and not place complex controls between methods like this.


Say you have

public void one() {
    System.out.println("Start of one.");
    two();
// do something
    System.out.println("End of one.");
}

public void two() {
    System.out.println("Start of two.");
    three();
// do something
    System.out.println("End of two.");
}

public void three() {
    System.out.println("Start of three.");
// do something
    System.out.println("End of three.");
}

You can add an unchecked exception if you cannot change two();

public void one() {
    System.out.println("Start of one.");
    try {
        two();
    } catch (CancellationException expected) {
    }
// do something
    System.out.println("End of one.");
}

public void two() {
    System.out.println("Start of two.");
    three();
// do something
    System.out.println("End of two.");
}

public void three() {
    System.out.println("Start of three.");
// do something
    System.out.println("End of three.");
    throw new CancellationException(); // use your own exception if possible.
}

You can return a boolean to say return, if you can change two()

public void one() {
    System.out.println("Start of one.");
    two();
// do something
    System.out.println("End of one.");
}

public void two() {
    System.out.println("Start of two.");
    if (three()) return;
// do something
    System.out.println("End of two.");
}

public boolean three() {
    System.out.println("Start of three.");
// do something
    System.out.println("End of three.");
    return true;
}

Or you can inline the structures

public void one() {
    System.out.println("Start of one.");
    two();
// do something
    System.out.println("End of one.");
}

public void two() {
    System.out.println("Start of two.");
    System.out.println("Start of three.");
// do something for three
    System.out.println("End of three.");
    boolean condition = true;
    if (!condition) {
// do something for two
        System.out.println("End of two.");
    }
}