What methods exist to interrupt the execution of a method?

    2 answers 2

    If the method returns nothing ( void ), then you can execute a return that terminates the operation of the method (or, more simply, exits it). Usage example

     public void foo(int n) { if(n < 0) return; else bar(n); } 

    In this case, before calling the bar method, there is a check for a negative number n .

    As for me, the return operator in void methods in 80% of cases can be replaced with some kind of logic, for example, the method above can be rewritten like this

     public void foo(int n) { if(n >= 0) bar(n); } 

    If the method returns something, then the return is always used (as it returns) and sometimes more than once (in methods with branching logic)

     public String foo(int n) { if(n == 1) return "ONE"; if(n == 2) return "TWO"; return "WTF!?"; } 

    @Regent in the comments corrected me. Since the return returns a value and finishes the method, the if/else ladder is not needed.

    • s/else //g to nothing they are here, all) - vp_arth
    • @vp_arth however if (x) { return foo; } else { return bar; } if (x) { return foo; } else { return bar; } if (x) { return foo; } else { return bar; } better perceived: "if something is done, then return the first, otherwise return the second." In general, a subjective thing: to specify an optional else or not. - Regent
    • @Regent, you are right. Why else here if there is a return - Flippy
    1. Using the operator return . return; for void methods and return value; for other methods.
    2. Throw an exception: throw new Exception(); . In this case, the method should have throws Exception . In practice, a specific exception is thrown (for example, IndexOutOfBoundsException ), often with an error text.

    Next are non-standard methods, which are rarely used in practice, but they still stop the execution of the method:

    1. System.exit(status); , aka Runtime.getRuntime().exit(status); . Stops the program.
    2. The deprecated stop method for Thread : Thread.currentThread().stop(); . About why he is deprecated, you can read here .