Domanda

Some explaination about the following snippets:
I'm messing with some Bluetooth discovery calls. For that I'm using a callback, which will be invoked if a BluetoothDevice is found or not. If no device was found the parameter is null:

@Override
public void provideDevice(BluetoothDevice device) {
    super.provideDevice(device);
    Log.v("MainActivity","device name = " +device.getName());
    if(device != null) {

        mBinder.start(device);

    } else { 

        Toast.makeText(this, "No Device found", Toast.LENGTH_SHORT).show();

    }
}

Eclipse is telling me that the else block is dead code.

If I move the Log call in the if-block the warning is gone:

@Override
public void provideDevice(BluetoothDevice device) {
    super.provideDevice(device);

    if(device != null) {

        Log.v("MainActivity","device name = " +device.getName());
        mBinder.start(bc);

    } else { 

        Toast.makeText(this, "No Device found", Toast.LENGTH_SHORT).show();

    }
}

I know that the first snippet will throw a NPE if the parameter is null. That's not the problem in this example.

I would like to know why the dead code warning appears.

I can provide the full code, if this isn't enough to tell me what's going on.

È stato utile?

Soluzione

You dereference device in the log statement.

If you get past that line of code, device cannot be null, because you'd get an NPE if it was.

This means the else statement is redundant, because if the code gets that far, it can't be null.

Altri suggerimenti

Your problem is that, in the first example, Java knows that it is impossible for device != null to be false, since if it were null, you would have gotten an NPE from the log statement, and would not reach that code.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top