繁体   English   中英

基于条件的Java程序结尾

[英]end of the program java based on condition

我有一个需要以顺序方式调用多个方法的要求。 但是,如果任何一种方法由于验证而失败,则程序不应继续。 我不能使用“引发异常,因为这些实际上不是异常,而不是满足我的要求的条件,并且在满足它之后,我不希望程序继续。

下面是一段代码示例和理解。 即使我使用Return,它仍然继续下一个方法。

public void method1(){
    System.out.println("Method 1");
    return;
}
public void method2(){
    System.out.println("Method 2");
    return;
}
public void method3(int a) throws Exception{
    System.out.println("Method 3");
    if (a==3) FinalMethod();
    return;
}
public void method4(){
    System.out.println("Method 4");
    return;
}
public void method5(){
    System.out.println("Method 5");
    return;
}

public void FinalMethod() {
System.out.println("This is the final method - end of the program");
return;
}

public void callMethod() throws Exception{
    method1();
    method2();
    method3(3);
    method4();
    method5();
}

方法callMethod将从Main方法中调用。 请帮助我学习。

编辑:如果method3中的参数为3,则应调用Finalmethod,然后程序应结束。 我不希望它用于method4和method5。

这些方法为什么不返回一个布尔值以确定下一个方法是否应该运行?

在这种情况下,在方法块末尾调用return是多余的。

假设您希望在出错时终止程序,则可以在catch使用System.exit(-1) (如果按照这种方式操作),或者在if语句中使用System.exit(-1) (如果这是您检查错误的方式)

编辑:我还应该澄清,使用System.exit(-1)与使用任何System.exit(n)其中n!= 0 System.exit(-1)相对没有特殊含义,除非在您自己的文档中另外指定

当您从method3调用FinalMethod时,这就是堆栈中正在发生的事情:

main-> callMethod-> method3-> FinalMethod

因此,当FinalMethod完成时,您将返回method3,然后从此处返回callMethod,并继续运行至最后。

我要做的是,如果要退出并就此调用它,则使method3返回一个布尔值:

public boolean method3(int a) {
    System.out.println("Method e");
    return a==3;
}

...

//In callMethod

if (method3(3)) { //If we want to exit after running method3
    FinalMethod();
    return;
}

尽管您可以使用System.exit(exitCode),但这不是一个好习惯,因为它违反了程序流程-程序只会在主函数的结尾处结束。

尽管method3当前引发了异常,但是您实际上并未在方法中引发异常。 但是,异常只能用于未定义的行为(特别是与您无法控制的情况有关,例如外部代码)。 最好提供一个用户友好的错误,并在可能的情况下继续执行该程序,否则,请正常退出。

不相关的提示:

  • 您不必在void函数的末尾调用return。
  • 默认情况下,您应该将方法设为私有,并且仅在需要时才将其公开

暂无
暂无

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

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