在 java 中处理异常后执行剩余代码?

Execute the remaining code after handling exception in java?

我可能是傻了。但是我接受了采访,有人问我如何 运行 得到异常后的剩余代码。

我给出了多种方法:

  1. We can write the code in finally.
  2. We can write the code in catch block. (They do not want to handle with these 2 approaches.)
  3. We can use throw keyword. But I tried practically, It's not working.

我也试着用 throw 语句来解释它们。

我参考了很多帖子。但是我的疑惑还是没有解开

例如,

  public static void main(String[] args)
  {
      a(); // getting exception here...
      b(); // This method should executed after handling exception
  } 

如果您能就此提出任何方法建议,将会很有帮助。这样我就明白了。

您需要在 where 或 finally 子句中执行方法

try {
  a(); // getting exception here...
} catch(Exception e) {
  b(); // This method should executed after handling exception
}

如果要执行b();只有在抛出异常时,您才应该在 catch(){} 块上调用它。如果无论如何你都想执行它,你可以把它放在 finally {} 上或者放在所有东西之后 (见编辑).

  • 如果b();非常反感异常或者你想使用在 try{} 块中初始化的变量,你应该在 finally{} 上这样写:

    try{
          a();
         } catch (Exception e){
          e.printStackTrace();
          //what to do if exception was thrown
         } finnaly {
          b();
         }
         //you can also call b(); here instead of inside finnaly
    
  • 如果b();然后用于处理异常:

    try{
     a();
    } catch (Exception e){
     e.printStackTrace();
     b();
    }
    

也可以让方法抛出A的异常,在调用a()的方法中处理;但是如果你是主力,你不应该那样做。

编辑: 根据要求,面试官要求的正确答案示例:

    try{
      a();
    } catch (Exception e){
      e.printStackTrace(); //optional
    }

    b();

对我来说,没有 try-catch-finally 的唯一简洁方法可能是使用 CompetableFuture 功能并将每个功能的执行分派为单独的任务。 像这样:

@Test
public void tryCatchFinallyWithCompletableFuture() throws Exception
{
    CompletableFuture
        .runAsync(
            () -> a()
        )
        .exceptionally(
            (e) -> { System.out.print(e.getMessage()); return null; }
        )
        .thenRun(
            () -> b()
        )
        .get();
}

static void a() {
    throw new IllegalStateException("a()");
}

static void b() {
    System.out.println("...but we continue after a()");
}

但是,我会认真考虑在 playground 项目以外的任何地方使用这种方法。此外,您必须记住 a()b() 是在 multi-threaded 上下文中执行的,如果存在共享状态,则可能需要同步共享状态。

如果您捕获并处理了异常,您可以在 try-catch 块之后 运行 您的 b() 方法:

try {
  a();
} catch(Exception e) {
  handleMyError(e);
}
b();

这样 a() 方法执行,如果抛出异常,它会在方法 handleMyError(Exception e) 中被捕获和处理,然后执行继续 to b() 无论异常是否被抛出或没有。