Stop executing further code in Java

后端 未结 6 1974
失恋的感觉
失恋的感觉 2021-01-01 16:25

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

相关标签:
6条回答
  • 2021-01-01 17:08

    You can just use return to end the method's execution

    0 讨论(0)
  • 2021-01-01 17:11

    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.

    0 讨论(0)
  • 2021-01-01 17:13

    There are two way to stop current method/process :

    1. Throwing Exception.
    2. returnning the value even if it is void method.

    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");
    }
    
    0 讨论(0)
  • 2021-01-01 17:14

    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);
        }
    
    0 讨论(0)
  • 2021-01-01 17:16

    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).

    0 讨论(0)
  • 2021-01-01 17:19

    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

    0 讨论(0)
提交回复
热议问题