I was following the flutter guide(fileio) of voiderealms(youtube)
and i had this problem on the function readfile, the editor says that is dead code but i dont know what does it mean
i have tried to search on the web
String readFile(String file) {
try {
File f = new File(file);
return f.readAsStringSync();
}
catch(e) {
print(e.toString());
}
}
main(List<String> arguments) {
String path = 'C:/Users/danis/Desktop';
String txtFile = 'C:/Users/danis/Desktop/test.txt';
list(path);
if(readFile(txtFile, 'Hello World\n', FileMode.APPEND));{
print(readFile(txtFile));
}
}
Due to the ; after the if the if statement gets seperated from the block ({}), which means that it always gets executed, no matter what the condition says. However that code is not "dead" as it actually gets executed.
What does [...] dead code [/unreachable code] in [a] programming language [mean]?
Dead code is code that is useless, because it will never execute. A function is dead if it is not called anywhere, statements can be dead if they are after a return or throw:
// 1
print("alive");
return;
print("dead");
// 2
if(false) print("dead");
This is a bit of code that will never be executed because it doesn't make sense.
For instance:
if (false) {
print("Hello World");
}
In your case you have such warning because you wrote:
if (something);
Notice the ;, it means that there's nothing to execute within the if.
DartAnalyzer warns about dead code when it can statically deduct that the code will under no circumstances be executed.
int fun() {
return 5;
print('x'); // dead code
}
int fun() {
if(true) {
print('x');
} else {
print('y'); // dead code
}
}
Related
EDIT: Ok, this is really stupid but I don't know why I didn't see it was a normal loop without the usual increments. I hope I was drunk when I posted this question because now I feel super idiot. Thanks anyway guys!
I'm following some tutorials on Java multi-threading in order to gather as much information and examples as possible.
On the Oracle website there is an official tutorial on Java Concurrency and I am looking at the Guarded Blocks section (here).
Whereas all the concepts are clear, I am reading the Producer/Consumer example at the bottom of the page and I do not understand some parts of the code.
Specifically, in the following is the code for the run() method of the Consumer class, where I do not understand how that for loop is supposed to work. It doesn't even look as it can work to me.
Can anyone explain me?
public void run() {
Random random = new Random();
for (String message = drop.take();
! message.equals("DONE");
message = drop.take()) {
System.out.format("MESSAGE RECEIVED: %s%n", message);
try {
Thread.sleep(random.nextInt(5000));
} catch (InterruptedException e) {}
}
}
It's just for loop being used in a non-idiomatic way.
You have the initialization String message = drop.take(); (instead of int i = 0;).
Then you have the test !message.equals("DONE"); (instead of i < 10).
Finally you have the "increment" or loop-advance or whatever the actual term is. Get the next value with message = drop.take(); (instead of i++).
Maybe it would be easier to understand when converted to a while-loop:
public void run() {
Random random = new Random();
String message = drop.take()
while (!message.equals("DONE")) {
System.out.format("MESSAGE RECEIVED: %s%n", message);
try {
Thread.sleep(random.nextInt(5000));
} catch (InterruptedException e) {}
message = drop.take()
}
}
Keep in mind that the for-loop generally consists of three parts:
for (INITIALIZATION; CONDITION; AFTERTHOUGHT)
{
// Code for the for-loop's body goes here.
}
INITIALIZATION is run once before the first iteration, CONDITION is checked prior to every iteration and AFTERTHOUGHT is executed after every iteration.
(Taken from https://en.wikipedia.org/wiki/For_loop#Traditional_for-loops)
So in this example, the INITIALIZATION of the for-loop creates the message variable and takes the first message from drop. It then checks it in the CONDITION block to see if its is anything but DONE. If it is, the loop body is executed once, printing the message and sleeping for up to 5000 milliseconds. Then the next message is taken in the AFTERTHOUGHT clause and the loops checks the CONDITION block again to either print the next message or leave the loop once it receives DONE.
I'm trying to do a recursion in Java. I just want to stop the recursion and continue normal prgram execution
void doit(){
try{
doit();
}
catch (StackOverflowError e) {
return;
}
System.out.println("Error");
}
statement1
doit()
statementcontinue
I want the program to continue execution to statementcontinue after the stackoverflow error
Your program is doing exactly what you told it to.
Each time you call doit(), it:
Calls doit() again
After that finishes, it prints Error.
When the stack overflow happens, the innermost call finishes (because of your return), and then continues executing the function that called it (like any other function call).
This is called popping the call stack.
The calling function (which is also doit()) then executes the next line (System.out.println("Error");), then returns to its calling function, which is also doit().
The cycle repeats until the stack is fully popped – until it gets up tothe function that originally called doit().
If you want to print "Error" only when the stackOverflow occurs, just place the trace in the catch block:
void doit(){
try{
doit();
}catch (StackOverflowError e) {
System.out.println("Error");
return;
}
}
Your code fills up the stack, then once the stack is full it hits the catch statement. After that the rest of the code continues to fire... each of those error messages is a recursive call that was made. Your code is working as you programmed it.
If you want an example of recursion that does stuff before and after, and has an exit condition, the following should work as an example for you (with print statements to clarify what is happening on the stack).
Example:
public class RecurseExample {
public static void main(String[] args) {
System.out.println("hi");
doIt(1);
System.out.println("bye");
}
private static void doIt(int i){
if (i <= 3){
System.out.println("i before: " + i);
doIt(++i);
System.out.println("i after: " + i);
} else {
System.out.println("this is where the recursion stops and the execution will continue to unravel the stack");
}
}
}
The output:
hi
i before: 1
i before: 2
i before: 3
this is where the recursion stops and the execution will continue to unravel the stack
i after: 4
i after: 3
i after: 2
bye
Should last statement be return in and non void return types method? But this is still working.
public String test()
{
try
{
// Do my work
return "myValue";
}
finally
{
System.out.println("I'm in Finally");
}
}
I'm bit lack of knowledge to understand how this work. Could someone explain me.
There is no problem with this code, because every possible path through it inevitably leads to a return statement*. It does not have to be the last statement textually, as long as it is the last statement logically (Java compiler is smart enough to figure out if it's so, and give you an error if there are paths through your code that do not return a value or throw an exception). The fact that there will be code executing after hitting the return (i.e. your finally block) does not change anything: as far as the compiler is concerned, your function has provided a return value before exiting the function.
* In fact, there is only one path through your function's code, and it terminates at the return statement.
It is sufficient in Java to make sure that all possible code paths either return a value or throw an exception. For example, the following code is valid:
public boolean test() {
if (3 < 5) {
return true;
} else {
throw new RuntimeException("Holy crap!");
}
}
In your example, your try block ends with a return, so the happy path is covered and there is no need for code beyond the finally; in addition, any exceptions thrown in the try will propagate out of the method and will have no chance to reach the end of the method, so all possible paths will never hit the section under the finally block and no return statement is needed. (In fact, a compiler may give you a warning or error about unreachable code if you added a return statement at the bottom!)
Things change when you add a catch clause, because now it's possible for code to flow beyond the try/catch/finally block:
public String test(){
try{
// Do my work
return "myValue";
}
catch (Exception ex) {
System.out.println("O noes something went wrong");
// swallow exception
}
finally {
System.out.println("I'm in Finally");
}
// Oh no! If an exception was caught, code can actually flow through here.
// Compiler will complain about a missing return statement until you add one.
// return "someOtherValue";
}
The key JLS concept for this is Normal and Abrupt Completion of Statements, combined with the behavior of try-finally.
The try block completes abruptly because of the return of "myValue". The finally block completes normally, so the whole try statement completes abruptly due to the same cause as the try block, return of "myValue".
In effect, the last statement in the method, the try statement, is one that returns a String.
In this case try and finally always execute. So, it doesn't matter where is return.
public String myfun(){
return "here";
}
or
public String myfun(){
try{
return "here";
}finally{
//will execute always
}
}
Are almost same. When, you see the flow of program. But, if there would be any conditional like
public String myfun(){
if(x==1){
return "here";
}
else{
// something here
}
}
In this case, it will raise error. Since, either any of the block will execute not both. Same as
public String fun(){
try{
return "here";
}
catch(Exception e){
//catch implementation without return
}
}
if (myCondition1 && myCondition2 && myCondition3)
{
...
}
I wrote this code and run successfully. but I got warning about part of (...). The warning is "Dead code". It is just interesting to me. Do u have any idea?
thank u
"Dead code" is code that will never be executed. Most likely one of your conditions is hard-coded to false somewhere, making the conditional inside the if always false.
Dead code means it is never going to execute. E.g.
void someMethod() {
System.out.println("Some text");
return;
System.out.println("Another Some text"); // this is dead code, because this will never be printed
}
Same in case of your condition checking e.g.
String obj = "";
if(obj == null && obj.equals("")) { // here you get warning for Dead code because obj is not null and first condition is false so obj.equals("") will never evaluate
}
Your code inside the block is never reached. The reason is most likely that one of the conditions is always false.
If one or more of myCondition1, myCondition2 and myCondition3 are always false (like private const bool myCondition1 = false;) then that code inside the if will never be executed.
This could occur for a number of reasons. Either the whole of the if block is dead, caused by something like the following:
boolean condition1 = true;
boolean condition 2 = !condition1;
if(condition1 && condition2) {
//This code is all dead
Foo f = fooFactory();
f.barr(new Bazz());
}
Or you unconditionally leave the if block using something like return, break or continue, as shown below:
for(Foo f : foos) {
if(true) {
f.barr(new Bazz());
break;
//Everything after here is dead
System.out.println("O noes. I won't get printed :(");
}
}
I have just encountered this following code:
public class TestFinally {
public static void main(String[] args) {
int returnValue = function();
System.out.println("Return value: " + returnValue);
}
public static int function() {
try {
return 1;
} catch (Exception e){
return 2;
} finally{
return 3;
}
}
}
It is without a doubt that running this code will yield an output of "Return value: 3".
However, I am curious as to:
The mechanism of the innards in the JVM. Does anyone know if the VM actually replaces the return value on the stack by over-writing the first "return 1"? If so, where can I find more information on this.
I have yet to find the use for a return in the finally mechanism that is used this way and allowed in the implemented
in the JVM. If this code construct is used as a means to return
error code, it is in my opinion there are better ways to log errors
or return these error codes. Has anyone found a use for such a
construct?
Many thanks in advance.
Cheers,
Vern
What I found in the Java language specification at least defines that your code snippet should return 3. Of course, it does not mention how the JVM should implement this, and what possible optimizations one could do.
Section 14.20.2 defines that
If execution of the try block completes abruptly for any other reason R, then the finally block is executed. Then there is a choice:
If the finally block completes normally, then the try statement completes abruptly for reason R.
If the finally block completes abruptly for reason S, then the try statement completes abruptly for reason S (and reason R is discarded).
And the start of chapter14 (section 14.1 to be more precise) specifies what a normal and abrupt completion is. For example a return with a given value is an abrupt completion.
Hence in this case, the finally block completes abruptly (reason: return with a given value), so the try will complete abruptly for the same reason (and return 3). This is confirmed in section 14.17 about the return statement as well
If evaluation of the Expression completes normally, producing a value V, then the return statement completes abruptly, the reason being a return with value V.
FWIW, I get a warning on function:
public static int function(){
try{
return 1;
}catch(Exception e){
return 2;
}finally{
return 3; //WARNING on this line
}
}
Ie. it tells me "finally block does not complete normally". I still get 3 as returned value no matter what.
Anyway, if I try this other example:
public class TestFinally {
public static void main(String[] args) {
int returnValue = function();
System.out.println("Return value: " + returnValue);
}
public static int function() {
try {
return 1;
}
catch (Exception e) {
return 2;
}
finally {
System.out.println("i don't know if this will get printed out.");
}
}
}
the output will be (obviously)
i don't know if this will get printed out.
Return value: 1
I have no idea how the JVM implements it, but the simplest way to look at it (at least conceptually) would be:
the return value in the "try" is pushed onto the stack,
then the "finally" block is executed,
the new return value is pushed onto the stack
the function exits, and the return value is popped from the stack, thus ignoring the first one.
Very neat question indeed.
The implementation is up to the JVM, and there are many JVMs. You could dig into OpenJDK's source code to see how it implements finally, but this wouldn't be the only way to do it. As far as the language is concerned, the important thing is the behavior.
I don't understand point 2 -- why does finally exist? it is not as you suggest somehow just a means to return an error code. You don't have to return from within finally at all. The construct exists to ensure that some kind of clean-up code is run after some section of code no matter how it terminates, whether normally or via exception or return.
Fully explained Page:439=>
http://docs.oracle.com/javase/specs/jls/se8/jls8.pdf
If evaluation of the Expression completes normally, producing a
value V, then the return statement completes abruptly, the reason being a return
with value V.
The preceding descriptions say "attempts to transfer control" rather than just "transfers
control" because if there are any try statements (§14.20) within the method or constructor
whose try blocks or catch clauses contain the return statement, then any finally
clauses of those try statements will be executed, in order, innermost to outermost, before
control is transferred to the invoker of the method or constructor. Abrupt completion of a
finally clause can disrupt the transfer of control initiated by a return statement.