How can I label and break out of a catch block?

Kröw :

I have a try...catch construct in my code somewhere:

try {
    // Some code.
} catch (Exception e) {
    if (condition) {
        // Break out of catch block.
    }
    // Continue catch block.
}

How can I label my catch block so that I can write break LABEL_NAME; in place of // Break out of catch block., so that execution will exit the try...catch construct entirely?

Attempts

I expected to be able to place a label before the catch keyword:

try { }
LBL: catch(Exception e) { }

as the label would go before the keyword in many other language constructs (e.g. LBL: if(... or LBL: for(...) but that raised a syntax error.

I wasn't able to place the label after the catch(Exception e) code either.

Edit

This question is purely out of curiosity for how one could accomplish this in Java. I am more than well aware that there are other ways to control flow of execution in a block of code.

If I'm ever to come across code that has labeled a catch or some similar block, and breaks from the block using the label, I'd like to know exactly what the code is doing and how it's doing it.

Kröw :

To break out of a catch, the try needs to be labeled:

LABEL: try {
   // Some code.
} catch(Exception e) {
   if(condition) {
      break LABEL;
   }
   // Remaining code.
}

Again, I'm sure there are plenty of better alternatives to this code, but this answers what the question is explicitly asking.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=308912&siteId=1
Recommended