Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: How to @SuppressWarnings unreachable code?

Sometimes when you are debugging, you have unreachable code fragment. Is there anyway to suppress the warning?

like image 595
Mohammad Moghimi Avatar asked May 17 '11 01:05

Mohammad Moghimi


People also ask

How do I fix unreachable code error in Java?

By performing semantic data flow analysis, the Java compiler checks that every statement is reachable and makes sure that there exists an execution path from the beginning of a constructor, method, instance initializer, or static initializer that contains the statement, to the statement itself.

Why am I getting unreachable code in Java?

Unreachable code error occurs when the code can't be compiled due to a variety of reasons, some of which include: infinite loop, return statement before the unreachable line of code.

How do you suppress a warning in Java?

Use of @SuppressWarnings is to suppress or ignore warnings coming from the compiler, i.e., the compiler will ignore warnings if any for that piece of code. 1. @SuppressWarnings("unchecked") public class Calculator { } - Here, it will ignore all unchecked warnings coming from that class.


1 Answers

Java has (primitive) support for debugging like this in that simple if on boolean constants will not generate such warnings (and, indeed when the evaluation is false the compiler will remove the entire conditioned block). So you can do:

if(false) {
    // code you don't want to run
    }

Likewise, if you are temporarily inserting an early termination for debugging, you might do it like so:

if(true) { return blah; }

or

if(true) { throw new RuntimeException("Blow Up!"); }

And note that the Java specification explicitly declares that constantly false conditional blocks are removed at compile time, and IIRC, constantly true ones have the condition removed. This includes such as:

public class Debug
{
static public final boolean ON=false;
}

...

if(Debug.ON) {
    ...
    }
like image 100
Lawrence Dol Avatar answered Oct 03 '22 20:10

Lawrence Dol