繁体   English   中英

Java:我已尝试,捕获并最终在java代码中,我想在try或catch块之后最终不执行

[英]Java: I have try,catch and finally in a java code and I want after try or catch block finally does not execute

我有以下代码

public class TEST
{
  public static void main(String arg[]){
    try
    {
      System.out.println("execute try");
      //what should I write hear that finally does not run.
    }
    catch (Exception e){
      System.out.println(e);
    }
    finally{
      System.out.println("execute finally");
    }
  }
}

我应该在最终不运行的try或catch块中写什么。 任何想法?

System.exit(0);

如果你想要一些不在“finally”块中运行的东西 - 不要把它放在“finally”中。 最后总是运行(好吧,除了像其他人提到的一些案例)。

您需要通过调用exit来关闭JVM

System.exit(exit_status);

来自Java文档

如果在执行try或catch代码时JVM 退出 ,则finally块可能无法执行。 同样,如果执行try或catch代码的线程被中断或终止,则即使应用程序作为一个整体继续,finally块也可能无法执行。

无论是否发生异常, 最终都意味着执行。 除非采用可疑的策略(正如约阿希姆所说的那样),这是无法避免的。

如果您在finally块中的代码不是每次都要执行,请不要使用finally构造; 请改用简单的if-construct

public class TEST
{
  public static void main(String arg[]){
    bool exitFinally  = false;
    try
    {
      System.out.println("execute try");
      //what should I write hear that finally does not run.
    }
    catch (Exception e){
      System.out.println(e);
    }
    finally{

        if(exitFinally)
            return;

      System.out.println("execute finally");
    }
  }
}

将代码最终放入if中。

public class TEST
{
  public static void main(String arg[]){
    boolean b = true;
    try
    {
      System.out.println("execute try");
      if (something()) b = false;
    }
    catch (Exception e){
      System.out.println(e);
    }
    finally{
      if (b){
        System.out.println("execute finally");
      }
    }
  }
}

使用布尔标志:

public class TEST
{
    public static void main(String arg[]){
        boolean success=false;
        try
        {
            System.out.println("execute try");
            //what should I write hear that finally does not run.
            success=true;
        }
        catch (Exception e){
            System.out.println(e);
        }
        finally{
            if (!success)
            {
                System.out.println("execute finally");
            }
        }
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM