What methods exist to interrupt the execution of a method?
2 answers
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 //gto 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 optionalelseor not. - Regent - @Regent, you are right. Why
elsehere if there is areturn- Flippy
- Using the operator
return.return;forvoidmethods andreturn value;for other methods. - Throw an exception:
throw new Exception();. In this case, the method should havethrows 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:
System.exit(status);, akaRuntime.getRuntime().exit(status);. Stops the program.- The deprecated
stopmethod forThread:Thread.currentThread().stop();. About why he is deprecated, you can read here .