How can I break from a try/catch block without throwing an exception in Java

后端 未结 6 1487
感动是毒
感动是毒 2021-02-01 12:29

I need a way to break from the middle of try/catch block without throwing an exception. Something that is similar to the break and continue in for loops. Is this possible?

6条回答
  •  独厮守ぢ
    2021-02-01 12:46

    Various ways:

    • return
    • break or continue when in a loop
    • break to label when in a labeled statement (see @aioobe's example)
    • break when in a switch statement.

    ...

    • System.exit() ... though that's probably not what you mean.

    In my opinion, "break to label" is the most natural (least contorted) way to do this if you just want to get out of a try/catch. But it could be confusing to novice Java programmers who have never encountered that Java construct.

    But while labels are obscure, in my opinion wrapping the code in a do ... while (false) so that you can use a break is a worse idea. This will confuse non-novices as well as novices. It is better for novices (and non-novices!) to learn about labeled statements.


    By the way, return works in the case where you need to break out of a finally. But you should avoid doing a return in a finally block because the semantics are a bit confusing, and liable to give the reader a headache.

提交回复
热议问题