I have looked in the Javadoc but couldn't find information related to this.
I want the application to stop executing a method if code in that method tells it to do so.
If that sentence was confusing, here's what I want to do in my code:
public void onClick(){
if(condition == true){
stopMethod(); //madeup code
}
string.setText("This string should not change if condition = true");
}
So if the boolean condition
is true, the method onClick
has to stop executing further code.
This is just an example. There are other ways for me to do what I am trying to accomplish in my application, but if this is possible, it would definitely help.
This question is related to
java
Just do:
public void onClick() {
if(condition == true) {
return;
}
string.setText("This string should not change if condition = true");
}
It's redundant to write if(condition == true)
, just write if(condition)
(This way, for example, you'll not write =
by mistake).
To stop executing java code just use this command:
System.exit(1);
After this command java stops immediately!
for example:
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
to come out of the method execution, break
to come out of a loop execution and continue
to skip the rest of the current loop. In your case, just return
, but if you are in a for loop, for example, do break
to stop the loop or continue
to skip to next step in the loop
You can just use return
to end the method's execution
There are two way to stop current method/process :
Option : you can also kill the current thread to stop it.
For example :
public void onClick(){
if(condition == true){
return;
<or>
throw new YourException();
}
string.setText("This string should not change if condition = true");
}
Either return;
from the method early, or throw
an exception.
There is no other way to prevent further code from being executed short of exiting the process completely.
Source: Stackoverflow.com