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.
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? 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.
A finally block always executes, regardless of whether an exception is thrown.
Definition and Usage. The return keyword finished the execution of a method, and can be used to return a value from a method.
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>
have a look at break
and continue
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With