Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Any easy way to get out of a Java block?

Tags:

java

I was just wondering if there is any way to get out of a Java block. It can be any block - if block, for block or even a simple {}. This is because I often come across such situations

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

This multiple levels of indentation clutters up the code I write.

Instead I need some way to do this

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 required processing outside the block. Would be nice if it doesn't involve writing that block within a try-catch block, creating a new exception type, throwing it and then catching it.

like image 875
Jagat Avatar asked Jul 01 '10 10:07

Jagat


People also ask

How do you exit a method in Java?

Exit a Java Method using Return return keyword completes execution of the method when used and returns the value from the function. The return keyword can be used to exit any method when it doesn't return any value.

What is block () in Java?

What is Block in Java? A block in Java is a set of code enclosed within curly braces { } within any class, method, or constructor. It begins with an opening brace ( { ) and ends with an closing braces ( } ). Between the opening and closing braces, we can write codes which may be a group of one or more statements.

Does the finally block always execute?

A finally block always executes, regardless of whether an exception is thrown.

Does return end a method Java?

Definition and Usage. The return keyword finished the execution of a method, and can be used to return a value from a method.


2 Answers

The correct construct to use is return. This implies that what is a block in your example should really be a method, but that is a good idea anyway - methods that are so long that they contain multiple, complicated control flow alternatives are an antipattern. Do yourself a favor and switch to "one objective per method" today! <end of evangelism>

like image 111
Kilian Foth Avatar answered Sep 19 '22 06:09

Kilian Foth


have a look at break and continue

like image 21
Thorbjørn Ravn Andersen Avatar answered Sep 22 '22 06:09

Thorbjørn Ravn Andersen