Any easy way to exit a Java block?

I'm just wondering if there is a way to exit the Java block. It can be any block - if block, for a block, or even a simple {}. This is due to the fact that I often encounter such situations.

{ retCode = performSomeThing(); if(retCode == SUCCESS) { retCode = performSomethingElse(); if(retCode == SUCCESS) { . . . . . . } } } 

These are several levels of indentation cluttering up the code I'm writing.

Instead, I need to do some way

 if((retCode = performSomething()) != SUCCESS) GET_OUT_OF_BLOCK if((retCode = performSomethingElse()) != SUCCESS) GET_OUT_OF_BLOCK 

Based on the value of retCode, I will perform any necessary processing outside the block. It would be nice if it were not related to writing this block in a try-catch block, creating a new type of exception, throwing it, and then catching it.

+6
java
source share
4 answers

The correct construct to use is return . This means that what is a block in your example should really be a method, but it’s a good idea, anyway, methods that take so long that they contain several complex control flow algorithms are antipater. Do yourself a favor and switch to “one goal per method” today! <end of evangelism>

+20
source share

take a look at break and continue

+7
source share

It seems you are using nested ifs to handle errors.

If you switch to handling structured exceptions, perhaps you could get rid of deeply nested if constructs altogether.

This, however, would mean that performSomeThing() and performSomethingElse() would throw exceptions instead of returning error codes.

+2
source share

<evangelism again>

Do not do this. In my opinion, the correct path for a block is one start at the beginning, one stop at the end, a complete stop.

Even with the method, you should only have one return at the end.

Inside the block, you write a stream of running instructions with if, etc., from beginning to end, the easier you can (so, sometimes you write return or break inside inside, ok; this should be the exception).

It’s best (but not necessary) to write normal completion statements .

-one
source share

All Articles