0

I have a variable which must be final for a reason. But while trying to assign a value to it, an Exception may be thrown in such case I need it to be 0. So I tried something like this.

private static final int x;

static {
    try {
        x = (1 / 0);
    } catch (Exception e) {
        x = 0; //error line
    }
}

Surprisingly it gives me a compile-time error saying,

variable x might already have been assigned.

I cannot understand this, x can only be assigned in try block OR in the catch block, possibly where else can a value be assigned to x? and how can I overcome this problem?


EDIT :

The best answer to this question is here by user NPE.

Roshana Pitigala
  • 8,437
  • 8
  • 49
  • 80
  • 3
    This is not a checked exception, but a compile time error. Since the `try`-block could be multi-lined and other lines after `x = (1 / 0);` could throw `Exception`s, the assignment in the `catch`-block could be a re-assignment, hence the compile time error. – Turing85 May 03 '18 at 17:39
  • @Turing85 I didn't see that, good point. Thanks. – Roshana Pitigala May 03 '18 at 17:53

0 Answers0