Tagged: catch

how to set final variable in catch block?


references

as final as possible, but not final-er.

꽤나 오랫동안 궁금했었다.

final SecureRandom random;
try {
    random = SecureRandom.getInstanceStrong();
} catch (final NoSuchAlgorithmException nsae) {
    random = new SecureRandom(); // won't compile
    // variable random might already have been assigned
}

let it go, let it go~~~

그냥 이렇게 하면 되지 뭐…

SecureRandom random;
try {
    random = SecureRandom.getInstanceStrong();
} catch (final NoSuchAlgorithmException nsae) {
    random = new SecureRandom();
}

// ----------------------------------
// 권팀장 죽어버려!!! -퇴사자-
random = null;
// ----------------------------------

final int i = random.nextInt(128); // NPE

we will find a way. we always have.

지저분해 보일지도 모르겠다.

final SecureRandom random;
{
    Random random_;
    try {
        random_ = SecureRandom.getInstanceStrong();
    } catch (final NoSuchAlgorithmException nsae) {
        random_ = new SecureRandom();
    }
    random = random_;
}

메서드로 따로 빼 놓고 써도 되고, 뭐…

static SecureRandom secureRandomPossiblyStrong() {
    try {
        return SecureRandom.getInstanceStrong();
    } catch (final NoSuchAlgorithmException nsae) {
        return new SecureRandom();
    }
}

Supplier 를 사용해도 될 듯…

final static SecureRandom RANDOM;
static {
    RANDOM = ((Supplier<SecureRandom>)() ->{
        try {
            return SecureRandom.getInstanceStrong();
        } catch (final NoSuchAlgorithmException nsae) {
            return new SecureRandom();
        } 
    }).get();
}