Why is the last line of this Java code unreachable - java

I've been writing a parse for a language and I am getting an unexpected problem in Java. Specifically, the Java compiler says that the return statement at the end of this code is unreachable.
StringBuffer buf = new StringBuffer();
Token tok2;
do {
tok2 = tokenizer.nextToken();
if (tok2 == null) throw new ParseException("Unexected end of file", tok2.endLine, tok2.endColumn);
switch (tok2.type) {
case Token.IDENTIFIER:
case Token.PACKAGE:
buf.append(tok2.token);
default:
throw new ParseException("Illegal character: expected identifier or .", tok.beginColumn, tok.beginLine);
}
} while (tok2.type != Token.SEMI_COLON);
return new PackageElement(buf.toString(), tok.beginLine, tok.beginColumn, tok2.endLine, tok2.endColumn);
tok2.type is an int, and the constants are ints, and the ParseException is a checked exception...
I understand what "unreachable" means and I have written many parses both from scratch and via tools like JavaCC, but I have been looking at this code for hours, and it seems correct to me...
Any help understanding why the return statement is unreachable would be much appreciated!

Your cases are missing breaks, which means each case falls through. That means that one of two things will happen:
if tok2 == null, an exception is thrown
otherwise, the switch block is triggered. Whether or not either case is hit, flow falls through to the default case, and an exception is thrown
In either case, the first run through the do block is guaranteed to throw an exception, and thus anything following it is unreachable.
Solution: add break statements, like this:
case Token.PACKAGE:
buf.append(tok2.token);
break; // <--- here
default:
// etc

Once you reach the semi colon token, the default case is hit and an exception thrown. This is the only exit from the loop.

You do not have a break statement anywhere, which means that the default statement is going to get executed - resulting in an Exception being thrown for certain no matter what. HEnce the return statement will never be hit.

Related

return boolean or try catch

when a function or method encouter error/invalid data, do return false or throw an exception?
Consider a class Loginer has such method :
public boolean login(String username){
//retrieve data...
if(username.equals(record.username)){
return true;
}
return false;
}
then at the main or some other class
String username = "ggwp";
if(Loginer.login(username)){
//successful login, show homepage...
new User(username);
} else {
//invalid username
}
won't it be inefficient as it has been checked two time with if-else statement, one in Loginer, and another one check for true again at main.
won't try catch will do the same? having the Loginer to throw an Exception:
public User login(String username){
//retrieve record data...
if(username.equals(record.username)){
return new User(username);
}
/* Exception if no record found for such username */
throw new MyException("invalid username");
}
then on the main:
String username = "ggwp2";
User theUser;
try{
//sucessful login
theUser = Loginer.login(username);
}catch(MyException e){
//invalid username
}
the try-catch need no check second time for true or false. (this example i use return User object, it could be void and return nothing but the point is, why use boolean which will eventual being check twice?)
some website sources say not to use try-catch for 'code jumping' but in this case it just do the same. (try-catch is just too similar to if-else statement)
So which is correct and why? please guide and sorry if this question is incorrect, im newbie to OO.
Short answer:
You should NEVER use try/catch for "control logic".
As Andy Turner said, "Use exceptions to handle exceptional conditions only."
This is equally true of all languages that support exceptions - not just Java. Useful article:
Best practices for exceptions
PS: try/catch is NOT "just similar" to "if/else". It has a different implementation, a different intent ... and it's FAR more expensive.
ADDITIONAL NOTE:
Exceptions: Why throw early? Why catch late?
https://softwareengineering.stackexchange.com/questions/231057/exceptions-why-throw-early-why-catch-late
In my experience, its best to throw exceptions at the point where the
errors occur. You do this because it's the point where you know the
most about why the exception was triggered.
As the exception unwinds back up the layers, catching and rethrowing
is a good way to add additional context to the exception. This can
mean throwing a different type of exception, but include the original
exception when you do this.
Eventually the exception will reach a layer where you are able to make
decisions on code flow (e.g a prompt the user for action). This is the
point where you should finally handle the exception and continue
normal execution.
With practice and experience with your code base it becomes quite easy
to judge when to add additional context to errors, and where it's most
sensible to actually, finally handle the errors.
Catch → Rethrow
Do this where you can usefully add more information that would save
a developer having to work through all the layers to understand the
problem.
Catch → Handle
Do this where you can make final decisions on what is an
appropriate, but different execution flow through the software.
Catch → Error Return
Whilst there are situations where this is appropriate, catching
exceptions and returning an error value to the caller should be
considered for refactoring into a Catch → Rethrow implementation.

Sequential throw declarations in my Java code

'Hi, everyone! I have a question about exception handling in Java. What is launched firstly if there is sequential "throw" declarations and why? Below is an example of a method like that:
public void myMethod(boolean ok) {
if (ok) {
// do something...
} else {
throw new myRuntimeException();
throw new RuntimeException ();
}
}
Thanks in advance!
Most compiler would flag the second "throw" as error : "Unreachable code" - as it will never get executed.
It would be like writing code after a return (except a finally block) - it is never going to get executed - hence illegal.
Once you throw, the flow of execution is interrupted and the following happens:
if you are inside a try block, it goes to to the corresponding catch
if not, the Throwable (Exception in your case) is passed up the call chain, leaving myMethod() and going to the method that called it
this process is repeated until you either reach a try block or the top of the call stack, in which case your program will terminate.
Thus, only your first exception is thrown, the throw new RuntimeException (); statement is never reached.

Exception handling in this scenario

Trying my hands on Java for the first time, please be kind. I have following code in a Web Controller where a service is called based on enclosed Switch-Case statement.
Issue I am facing is, if the service call throws an Exception, this exception gets shown on the JSP page. Basically the code never reaches the lines:
if(!statusFlag)
{
model.addAttribute("statusFlag", statusFlag);
return "myJspPage"
}
How do I make sure the executing goes to above lines, even though an exception is thrown in the WebService call at:
statusFlag = myWebService.getMeStatus();
Should I enclose the whole Switch Statement inside try-catch block?
Snippet:
#Controller
public String mySpringController() throws Exception
{
//rest of the controller code
switch ( condition )
{
case MAY :
statusFlag = myWebService.getMeStatus();
if(!statusFlag)
{
model.addAttribute("statusFlag", statusFlag);
return "myJspPage"
}
break;
case JUNE :
statusFlag = myWebService.getMeStatus();
if(!statusFlag)
{
model.addAttribute("statusFlag", statusFlag);
return "myJspPage"
}
break;
case JULY :
statusFlag = myWebService.getMeStatus();
if(!statusFlag)
{
model.addAttribute("statusFlag", statusFlag);
return "myJspPage"
}
break;
default:
//Do something by default.
}
return "myJspPage";
}
If that line is throwing an Exception it means that it is never returning, so statusFlag is still with its original value and the execution of that method has stopped. You need to surround it in a try - catch if you want to catch the Exception and do something about it.
I see you are using Spring. In Spring Controllers you can also have your own special methods which get invoked when an Exception occurs. Using the #ExceptionHandler annotation.
I don't see the purpose of your switch statement since each case does the same thing.
But basically you can put your webservice call in a try-catch block
try{
webservice.call();
}
catch (Exception e){
// handle the exception
}
finally{
//anything in here will be executed regardless if an exception is caught or not
}
You're writing Java in the style of C++, where you're returning error codes and then checking them to determine whether anything went wrong. There are a number of issues with this snippet, but the reason for the exception display is that you never catch the exception that's being thrown. Where you should put your try-catch block depends on what the exception means; if it's something that isn't specific to a particular month, then yes, enclose the entire switch statement to share the error handling.
As an aside, did you copy and paste your actual code, or did you try to retype an example? Those case blocks all look identical.

Using try-catch -- Skipping try

I'm trying to write a code that I can try a JSON object and if it's the wrong format inform the user somehow.
The code is :
public boolean sjekkSporingsNummer (JSONObject object){ //object is passed correct
Boolean riktigSporing = null;
riktigSporing = true; //riktig sporing is set to true
//if its true the json is correct
try {
JSONArray consignmentSet = object.getJSONArray("consignmentSet");
JSONObject object1 = consignmentSet.getJSONObject(0);
riktigSporing = true;
}catch (Exception e){ //skips straigt to here
e.printStackTrace();
riktigSporing = false;
}
return riktigSporing;
After if failes with :
07-31 12:34:07.243 15479-15479/com.example.posten E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.NullPointerException
What seems wierd to me is that my app skips the try and goes straight to the return statement.
I would like it to try and of it failes set "riktigSporing" to false.
What am I doing wrong?
I bet it doesn't. I suspect your input parameter is null and you trigger an NPE very early.
Note also you could possibly unbox a null into a primitive boolean, and that won't work.
EDIT:
FATAL EXCEPTION: main
java.lang.NullPointerException
suggests this further. You should have a corresponding line number in your stacktrace.
Most probably you get an exception at the first line in the try block.
I think there is a better approach to code this method. Do not use boolean to show how successful was this method execution. If this method executes ok, then return nothing. But if there's an error upon execution, throw an exception specific to the error you have got.
Avoid use of general exception classes where possible. Use exception classes specific to a sitiation which caused the problem. I.e NullPointerException, JSONException, NumberFormatException and so on. If there's a custom specific possible reason or reasons for exceptions then make your custom exception class and throw it when necessary to mark the problem as precise as possible.
It will let the caller process this error properly or throw this exception further.
In general this approach makes your application more consistent and manageable.
You need to set your boolean in this catch:
catch (JSONException e) {
e.printStackTrace();
riktigSporing = false;
}
In the case of some error with JSON this catch will be called, not second one. I think in your scenario your second catch is not required.
If you want to use generally Exception, remove JSONException and let there only Exception
Note: When i looked at your snippet of code, i suggest you to use boolean as primitive data-type instead of Boolean. It will be more clear and efficient.
It is impossible. I think try block is executed without a exception thrown and thus it must go to return statement. Or else your code might not have build properly.

Java If -else statement not working as expected

So I'm making a program on a pretty low level of Java-programming.
This is what I'm having problems with:
//The String fillText is given a value earlier in the program
if ("".equals(txa1.getText()))
{
txa1.setText(fillText);
txa1.setVisible(true);
}
else if ("".equals(txa2.getText()))
{
txa2.setText(fillText);
txa2.setVisible(true);
}
else if ("".equals(txa3.getText()))
{
txa3.setText(fillText);
txa3.setVisible(true);
}
else if ("".equals(txa4.getText()))
{
txa4.setText(fillText);
txa4.setVisible(true);
}
else if ("".equals(txa5.getText()))
{
txa5.setText(fillText);
txa5.setVisible(true);
}
...
This code appears to ALWAYS fill all of the textareas (txaX) with fillText.
I was expecting it to only execute the first of the statements that returned true and then break out of the if-else-statement.
I tried to do it with a switch-case, but ended up failing since the String is changed during the run of the program.
What is wrong?
Thanks in advance!
It is in loop .Definetely that is causing the problem.With out loop it will go to only one block.It is not possible too execute without loop.When ever we are using if else only one block will execute.
"".equals(txa1.getText())
I think above condition for each returns true.
getText() method is always returning empty string i.e "";
You have to carefully examine your conditions, it'll basically execute the predecessors if the condition is false.
I suggest you think more on the logic of what you are trying to achieve..

Categories