停止在Java中执行更多代码
我查看了Javadoc但找不到与此相关的信息。
我希望应用程序停止执行方法,如果该方法中的代码告诉它这样做。
如果那句话令人困惑,这就是我想在我的代码中做的事情:
public void onClick(){ if(condition == true){ stopMethod(); //madeup code } string.setText("This string should not change if condition = true"); }
因此,如果布尔condition
为真,则onClick
方法必须停止执行更多代码。
这只是一个例子。 还有其他方法可以让我在我的应用程序中完成我想要完成的任务,但如果可行,那肯定会有所帮助。
做就是了:
public void onClick() { if(condition == true) { return; } string.setText("This string should not change if condition = true"); }
写if(condition == true)
是多余的,只写if(condition)
(这样,例如,你不会写=
错误)。
return
退出方法执行, break
循环执行并continue
跳过当前循环的其余部分。 在你的情况下,只return
,但是如果你在for循环中,例如, break
以停止循环或continue
跳到循环中的下一步
有两种方法可以阻止当前的方法/过程:
- 抛出exception。
- 即使它是无效方法也返回该值。
选项:你也可以杀死当前线程来阻止它。
例如 :
public void onClick(){ if(condition == true){ return; throw new YourException(); } string.setText("This string should not change if condition = true"); }
要停止执行java代码,只需使用以下命令:
System.exit(1);
执行此命令后,java立即停止!
例如:
int i = 5; if (i == 5) { System.out.println("All is fine...java programm executes without problem"); } else { System.out.println("ERROR occured :::: java programm has stopped!!!"); System.exit(1); }
您可以使用return
来结束方法的执行
要么return;
从方法早,或throw
exception。
除了完全退出进程之外,没有其他方法可以防止执行进一步的代码。