Initialize the final instance variable of inner class

java

Solution

The problem is not that you are trying to initialize the field in constructor, but the fact that you don't initialize it in the `catch` block. The compiler must be sure that the field will always get initialized before exiting constructor.

Unfortunately, simply assigning a fallback value in the `catch` block will not work, because when compiler sees code like this:

try {
    ...
    someFinalField = ...
    ...
} catch {
    ...
    someFinalField = ...
    ...
}

... then it sees a possibility for the field to be initialized twice (once in the `try` block and second time in the `catch` block), which is illegal for `final` fields. In your simple case we clearly see that this is impossible, because the exception will always be thrown before the field is initialized in the `try` block, but unfortunately the compiler isn't smart enough to understand that.

You can satisfy the compiler by throwing an exception from the `catch` block, which would probably be a preferred option in your case:

catch (IOException e) {
    throw new RuntimeException(e);
}

or, using very popular guava library

catch (IOException e) {
    throw Throwables.propagate(e);
}

If you really want to swallow the exception, then - to ensure that the field always gets initialized exactly once, you have to move the initialization outside of `try-catch` block:

private class AcceptThread extends Thread {
    private final BluetoothServerSocket mBluetoothServerSocket;
    public AcceptThread() {
        BluetoothServerSocket localBluetoothServerSocket;
        try {
            localBluetoothServerSocket = ...
        } catch (IOException e) { 
            localBluetoothServerSocket = ...
        }
        mBluetoothServerSocket = localBluetoothServerSocket;
    }
}

Problem

Hello I want to initialize the final variable of inner class in it constructor but compiler forcing me to initialize it at the time of declaration Why Any idea ? How can I handle this situation ? ``` public MainActivity extends Activity { private class AcceptThread extends Thread { private final BluetoothServerSocket mBluetoothServerSocket; public AcceptThread() { try { mBluetoothServerSocket = mBluetoothAdapter.listenUsingRfcommWithServiceRecord("BT_SERVER", UUID.fromString("a60f35f0-b93a-11de-8a39-08002009c666")); } catch (IOException e) { } } // Here methods } } ``` See here who answered to my question that seems weird here

Original source