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

后端 未结 6 1416
感动是毒
感动是毒 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:56

    The proper way to do it is probably to break down the method by putting the try-catch block in a separate method, and use a return statement:

    public void someMethod() {
        try {
            ...
            if (condition)
                return;
            ...
        } catch (SomeException e) {
            ...
        }
    }
    

    If the code involves lots of local variables, you may also consider using a break from a labeled block, as suggested by Stephen C:

    label: try {
        ...
        if (condition)
            break label;
        ...
    } catch (SomeException e) {
        ...
    }
    

提交回复
热议问题