我正在寻找某种语句或函数,当命中时,它不仅会退出当前方法(方法1(,还会退出当前方法嵌套的所有方法(方法2、3和4(,而不会退出程序(我想在运行时停止(。
我希望有一种替代方法,可以有条件地检查调用(或可能调用(方法1的每个实例。谢谢
import java.awt.EventQueue;
public class ExitTest implements Runnable {
public static void main(String[] args) {
EventQueue.invokeLater(new ExitTest());
}
@Override
public void run() {
method4();
}
public void method1() {
System.out.println("I want this line to hit.");
// Looking for something here that exits all nested methods
}
public void method2() {
method1();
System.out.println("I don't want this line to hit.");
}
public void method3() {
method2();
System.out.println("I don't want this line to hit.");
}
public void method4() {
method3();
System.out.println("I don't want this line to hit.");
}
}
正如大家所说,您可以在方法1中抛出异常,并在方法4中处理异常,如下所示。
public class Main {
public static void main(String[] args) {
new Main().run();
}
public void run() {
System.out.println("Calling method 4");
try {
method4();
}catch(Exception e){ }
System.out.println("Return from method 4");
}
public void method1() {
System.out.println("I want this line to hit.");
throw new RuntimeException();
}
public void method2() {
method1();
System.out.println("I don't want this line to hit.");
}
public void method3() {
method2();
System.out.println("I don't want this line to hit.");
}
public void method4() {
method3();
System.out.println("I don't want this line to hit.");
}
}