0

If the code faced a specific case I want to stop the current execution but continue the parent loop.

main() {
     while(line not empty) {
         // blablabla
         method1()
         // tadatadatada
    }
}

method1() {
    // blablabla
    method2()
   // etcetcetc
}

method2() {
    // blablabla
    if (var == 1)
        stop the execution of the current method and parent method
    // etcetcetc
}

In the case explained below, if var == 1, all etcetcetc part of code must not be executed, but tadatadatada must be...

So I want to stop all children executions.

Is there a solution to do that in Java?

Federico klez Culloca
  • 26,308
  • 17
  • 56
  • 95
Royce
  • 1,557
  • 5
  • 19
  • 44
  • 2
    You can just `return;` from a method... But I think your example is not sufficient to give that as an answer... Show us the real implementation, please. – deHaar Oct 28 '19 at 15:55
  • thank you for your answer. However, if I use `return;` in `method2`, code `etcetcetc` will be executed in `method1`... – Royce Oct 28 '19 at 15:56
  • 1
    You know, that's why I was asking for the real code... I can't tell you from what you have posted so far. Maybe it is not possible to just `return;` in this use case, but nobody will know that without the code. – deHaar Oct 28 '19 at 15:59
  • you can make method2 return false if you want to quit and then in method1 put the return of method2 in a variable e.g. result=method2(); then check outside if (result==false) break; – Amany Oct 28 '19 at 16:00

2 Answers2

0

Return a value from method2 and check it in method1. If it meets a condition, return from method1 too.

Something like:

method1() {
  var shouldBreak = method2();
  if (shouldBreak) {
    return 
  }
  // more stuff
}
itzhaki
  • 822
  • 2
  • 7
  • 19
0

Look into Java Multithreading. This will allow you to run multiple methods simultaneously and give you full control over when to stop a specific thread.

Here's a starting point from another: Threads in Java

I don't quite understand fully what you're asking as your example doesn't have extensive clarity, but hopefully this is what you're looking for.