I Can Hardly Reach! 20/100 Days of Code
Writing void methods? Piece of cake. Writing methods with return types? Well…That’s another story
I spent over an hour staring at my screen when a method of return type String kept having errors. I used nested if statements to test something, and I kept getting a warning that I was missing a curly brace.
I tried adding the brace, but I got a warning about the method returning a String
Turns out I was missing a return statement in one of the if statements. Since the method is of type String, it must always return a String. However, if the program processes an if statement that prevents the method from returning a String, it creates an error (click the example below)
If g < 0 the program will not return a String. It will print the statement “Inner is false”, and stop running. However, this creates an error since the getItNow() method should return a String.
Dealing with a series of if statements can get confusing and lead to some problems if done incorrectly. Each flow of logic in the program must return a String and every statement written must be reachable in some way. (click the example below)
While testing, I came across an error called an Unreachable Statement. Unreachable Occur when a statement is incapable of being executed. One of the return statements I wrote was obscured and the program had no way to execute it.
Unreachable statements can only be fixed by being made executable. In my program, it occurred because of a return statement that couldn’t be executed.
Most programming languages are built with checks for this error. It prevents bugs that could be caused by ignored lines of code. I’m glad I came across this error. I have a little more understanding about programming languages. Just another one of the goofy little things that make programming so much fun! I left a couple links to more information below for both Java and JavaScript.
Java Unreachable
JS Unreachable
-CF