Could a final variable be reassigned in catch, even if assignment is last operation in try?

前端 未结 12 1158
粉色の甜心
粉色の甜心 2020-12-04 18:49

I am quite convinced that here

final int i;
try { i = calculateIndex(); }
catch (Exception e) { i = 1; }

i cannot possibly have

12条回答
  •  心在旅途
    2020-12-04 19:44

    I faced EXACTLY the same problem Mario, and read this very interresting discussion. I just solved my issue by that:

    private final int i;
    
    public Byte(String hex) {
        int calc;
        try {
            calc = Integer.parseInt(hex, 16);
        } catch (NumberFormatException e) {
            calc = 0;
        }
        finally {
          i = calc;
        }
    }
    

    @Joeg, I must admit that I liked a lot your post about design, especially that sentence: calculateIndx() calculates sometimes the index, but could we say the same about parseInt() ? Isn't that also the role of calculateIndex() to throw and thus not calculate the index when it is not possible, and then making it returning a wrong value (1 is arbitrary in your refactoring) is imho bad.

    @Marko, I didn't understand your reply to Joeg about the AFTER line 4 and BEFORE line 5... I'm not strong enough yet in java world (25y of c++ but only 1 in java...), but I thing this case is one where the compiler is right : i could be initialized twice in Joeg's case.

    [All what I'm saying is a very very humble opinion]

提交回复
热议问题