【问题标题】:Is it possible to return from a method to lets say是否可以从一种方法返回让我们说
【发布时间】:2023-03-23 07:08:01
【问题描述】:

有 f1、f2 和 f3 三种方法。我想从 f3 回到 f1。

假设:

最初 f1 调用 f2

f2 调用 f3。

Try catch 块应该用在所有三个函数中。

如果我在 f3 中遇到异常,那么我应该能够返回到 f1。

谢谢。

【问题讨论】:

  • 试试/终于是你的朋友了。
  • 如果我在 f3 中使用 try catch 并且如果我在 f3 的 catch 中使用 return。然后它返回到 f2。我想要的是没有任何条件检查它应该能够返回到 f1。
  • 您应该实现一些状态标志来确定何时从 f2 返回到 f1,但这确实需要条件检查。
  • @ExtremeCoders 我试图避免使用状态标志,因为与 f3 处于同一级别的函数数量很多。

标签: java exception methods return


【解决方案1】:
catch(Exception e) { 
return;
}

您可以在 f2 中捕获异常并添加 return 以便它将转到 f1。或者只是不捕获 f2 中的异常(只需在 f2 中添加 throws)并让它传播到 f1。

【讨论】:

    【解决方案2】:

    试试..

    void f1(){
    
    try{
    f2();
    }catch(Exception er){}
    system.out.println("Exception...");
    
    }
    
    void f2() throws Exception{
    
    f3();
    
    }
    
    void f3() throws Exception{
    
    //on some condition
    throw new Exception("something failed");
    
    }
    

    【讨论】:

    • 我已编辑问题,请查看。谢谢。
    【解决方案3】:

    试试

    public void f1(){
        f2();
        // f3 failed. other code here
    }
    
    public void f2(){
        try {
            f3();
        } catch (Exception e){
            // Log your exception here
        }
        return;
    }
    
    public void f3(){
        throw new Exception("Error:");
    }
    

    【讨论】:

    • 所有函数都应该使用try catch块
    • 不需要。在 f2 中,您将记录错误并 f2 返回。然后 f1 的剩余部分被执行
    【解决方案4】:

    检查类似的东西

    void f1() throws Exception {
    
        try {
            f2();
        } catch (Exception e) {
            throw new Exception("Exception Ocuured");
        }
    
    
    }
    
    void f2() throws Exception {
        try {
            f3();
        } catch (Exception e) {
            throw new Exception("Exception Ocuured");
        }
    }
    
    void f3() throws Exception {
    
        try {
    
            // Do Some work here
        } catch (Exception e) {
            f1();
    
    
        }
    }
    

    【讨论】:

    • 在 f3() 的 catch 块中调用 f1() 会从头开始执行 f1 中的语句。执行后返回f3,f3返回f2,f2中的语句在我们调用f3之后的语句将被执行,之后返回f1。这不是我需要的行为。谢谢。
    猜你喜欢
    • 2016-10-12
    • 1970-01-01
    • 1970-01-01
    • 2017-02-15
    • 1970-01-01
    • 1970-01-01
    • 2015-10-09
    • 2012-12-02
    • 1970-01-01
    相关资源
    最近更新 更多