【问题标题】:In Java, is there a way to exit a method that will also exit all vertically nested methods?在 Java 中,有没有办法退出一个也将退出所有垂直嵌套方法的方法?
【发布时间】:2021-12-31 15:57:52
【问题描述】:

我正在寻找某种语句或函数,当它被命中时,不仅会退出当前方法(方法 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.");
    }
}

【问题讨论】:

  • 没有。高层次地告诉我们你真正想做的事情。
  • 你可以抛出异常并在run方法中捕获它。这是尽可能接近的。
  • 那么,程序如何知道何时停止退出方法?我假设您不想退出run,但runmethod2method3 等有何不同?
  • 这几乎是例外的重点。放try{ method4(); } catch(RuntimeException e){ ...} 你可以让它在你处理它之前随心所欲地放在堆栈上,或者处理并重新抛出。

标签: java methods exit


【解决方案1】:

正如大家所说,你可以在方法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.");
    }
}

【讨论】:

  • 既不捕捉一般的“异常”也不捕捉不太一般的“RuntimeException”。为您的用例创建自己的异常类!
  • 虽然OP有点含糊。您可能应该将 throw 子句放在不会处理异常的方法上,这样它在 API 中是明确的。
  • 如果涉及线程,创建 UncaughtExceptionHandler 会非常有用。
猜你喜欢
  • 2022-01-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-06
  • 2022-07-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多