59

I am quite convinced that here

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

i cannot possibly have already been assigned if control reaches the catch-block. However, Java compiler disagrees and claims the final local variable i may already have been assigned.

Is there still some subtlety I am missing here, or is this just a weakness of the model used by the Java Language Specification to identify potential reassignments? My main worry are things like Thread.stop(), which may result in an exception being thrown "out of thin air," but I still don't see how it could be thrown after the assignment, which is apparently the very last action within the try-block.

The idiom above, if allowed, would make many of my methods simpler. Note that this use case has first-class support in languages, such as Scala, which consistently employ the Maybe monad:

final int i = calculateIndex().getOrElse(1);

I think this use case serves as a quite good motivation to allow that one special case where i is definitely unassigned within the catch-block.

UPDATE

After some thought I am even more certain that this is just a weakness of the JLS model: if I declare the axiom "in the presented example, i is definitely unassigned when control reaches the catch-block", it will not conflict with any other axiom or theorem. The compiler will not allow any reading of i before it is assigned in the catch-block, so the fact whether i has been assigned to or not cannot be observed.

6
  • 1
    If this were valid, then adding subsequent statements in the try block, completely unrelated to i, could cause a compile error in the catch block on the assignment to i. I would find that surprising. Jun 12, 2013 at 21:09
  • 1
    @AndyThomas I'd find it quite intuitive that i may have been assigned if there are more statements following the assignment. Jun 12, 2013 at 21:27
  • If you are looking for a Scala-like construct you cal always use Guava's Optional.
    – fge
    Jun 17, 2013 at 17:35
  • @fge I have been resisting the temptations of Guava for several years now. I regularly find yet another feature that I could use, but still decide to bake my own. The barrier to the DYI way is too low for most Guava features, and DYI tends to be more fun for me :) Jun 17, 2013 at 18:41
  • What is interesting, given the conversation below, is to change the catch() block to instead use i, for example just a println(i). In that case the compiler will give the error: variable i might not have been initialized. Both error messages are non-committal (may have been initialized, might not have been); likely, but not guaranteed. Jun 20, 2013 at 15:59

12 Answers 12

35

JLS hunting:

It is a compile-time error if a final variable is assigned to unless it is definitely unassigned (§16) immediately prior to the assignment.

Quoth chapter 16:

V is definitely unassigned before a catch block iff all of the following conditions hold:

V is definitely unassigned after the try block.
V is definitely unassigned before every return statement that belongs to the try block.
V is definitely unassigned after e in every statement of the form throw e that belongs to the try block.
V is definitely unassigned after every assert statement that occurs in the try block.
V is definitely unassigned before every break statement that belongs to the try block and whose break target contains (or is) the try statement.
V is definitely unassigned before every continue statement that belongs to the try block and whose continue target contains the try statement.

Bold is mine. After the try block it is unclear whether i is assigned.

Furthermore in the example

final int i;
try {
    i = foo();
    bar();
}
catch(Exception e) { // e might come from bar
    i = 1;
}

The bold text is the only condition preventing the actual erroneous assignment i=1 from being illegal. So this is sufficient to prove that a finer condition of "definitely unassigned" is necessary to allow the code in your original post.

If the spec were revised to replace this condition with

V is definitely unassigned after the try block, if the catch block catches an unchecked exception.
V is definitely unassigned before the last statement capable of throwing an exception of a type caught by the catch block, if the catch block catches an unchecked exception.

Then I believe your code would be legal. (To the best of my ad-hoc analysis.)

I submitted a JSR for this, which I expect to be ignored but I was curious to see how these are handled. Technically fax number is a required field, I hope it won't do too much damage if I entered +1-000-000-000 there.

8
  • I was there too but can't conclude. does i = m(); qualify if m can throw an exception?
    – assylias
    Jun 12, 2013 at 20:58
  • 1
    Yes, that's the model whose weakness I am asking about in the question. Jun 12, 2013 at 20:58
  • @assylias It is certainly true that V is not definitely unassigned after the try-block. A finer analysis is required to realize that the fact that execution flow finds itself within the catch-block is sufficient to prove that V is definitely unassigned. Jun 12, 2013 at 21:02
  • @MarkoTopolnik updated answer. This is as far as I can go with my Java expertise, you'll need a real language lawyer or Java historian to go further.
    – djechlin
    Jun 12, 2013 at 21:08
  • I was careful to avoid a "historical why" question since that's unanswerable. My interest is only whether this model is fixable, or some important subtlety prevents fixing. Jun 12, 2013 at 21:14
20
+200

I think the JVM is, sadly, correct. While intuitively correct from looking at the code, it makes sense in the context of looking at the IL. I created a simple run() method that mostly mimics your case (simplified comments here):

0: aload_0
1: invokevirtual  #5; // calculateIndex
4: istore_1
5: goto  17
// here's the catch block
17: // is after the catch

So, while you can't easily write code to test this, because it won't compile, the invoke of the method, the store the value, and the skip to after the catch are three separate operations. You could (however unlikely that may be) have an exception occur (Thread.interrupt() seems to be the best example) between step 4 and step 5. This would result in entering into the catch block after i has been set.

I'm not sure you could intentionally make that happen with a ton of threads and interrupts (and the compiler won't let you write that code anyway), but it is thus theoretically possible that i could be set, and you could enter in the exception handling block, even with this simple code.

6
  • You are making a good case here. Take note that the variable could still be treated as definitely unassigned, which implies it can't be read until written. The program would have no chance to see the write. However, taking into account the point made by @amadeus about the Virtual Machine Tool Interface, it could mean that this would cause trouble. I am not acquainted with the VMTI enough to know if this concern is real. Jun 20, 2013 at 19:16
  • 1
    BTW Thread#interrupt can't do anything interesting; only Thread#stop can. Jun 20, 2013 at 19:39
  • I have found a key counterargument to the "tooling" argument: the debug tool must be aware which variables are definitely assigned at each point in code, and never show the value of any other vars. This would preclude making an accidental assignment before the goto observable. Jun 20, 2013 at 20:02
  • I think that's the problem - you can't assume that the variable is definitely unassigned, because if step 4 complete, the variable is assigned. However unlikely the case may be, it's possible, thus has to be assumed as a valid condition. I'd consider it a case where intuition breaks down when working with higher-level languages. What looks like a single instruction in Java is still many instructions at a lower level. And a signal can occur at any point. It's a good question how VMTI would interpret this; but in practice it's so unlikely to ever occur. Jun 21, 2013 at 0:28
  • As I point out in my question: if I declare the axiom "i is definitely unassigned when control reaches the catch-block", it will not conflict with any other axiom or theorem. The compiler will not allow any reading of i before it is assigned in the catch-block, so the fact whether i has been assigned to or not cannot be observed. Jun 21, 2013 at 5:04
7

Not quite as clean (and I suspect what you are already doing). But this only adds 1 extra line.

final int i;
int temp;
try { temp = calculateIndex(); }
catch (IOException e) { temp = 1; }
i = temp;
4
  • Would it be a good idea to put the assignment in a finally block?
    – A4L
    Jun 12, 2013 at 20:55
  • Actually I just remove final. It's there because final variables make my code easier to follow, so it's not mandatory. If it were, I'd probably go for a method that contains the try-catch and returns an exception-free value. Jun 12, 2013 at 20:56
  • 1
    It's actually kind of interesting that it's able to determine temp is definitely assigned after the catch block, but not that it's definitely unassigned before the catch block.
    – djechlin
    Jun 12, 2013 at 21:27
  • @djechlin That's because if control reaches the point after the catch, it means that it completed normally. Not so with the try block. Jun 13, 2013 at 9:42
4

This is a summary of the strongest arguments in favor of the thesis that the current rules for definite assignment cannot be relaxed without breaking consistency (A), followed by my counterarguments (B):

  • A: on the bytecode level the write to the variable is not the last instruction within the try-block: for example, the last instruction will typically be a goto jump over the exception handling code;

  • B: but if the rules state that i is definitely unassigned within the catch-block, its value may not be observed. An unobservable value is as good as no value;

  • A: even if the compiler declares i as definitely unassigned, a debug tool could still see the value;

  • B: in fact, a debug tool could always access an uninitialized local variable, which will on a typical implementation have any arbitrary value. There is no essential difference between an uninitialized variable and a variable whose initialization completed abruptly after the actual write having occurred. Regardless of the special case under consideration here, the tool must always use additional metadata to know for each local variable the range of instructions where that variable is definitely assigned and only allow its value to be observed while execution finds itself within the range.

Final Conclusion:

The specification could consistently receive more fine-grained rules which would allow my posted example to compile.

3

You are correct that if the assignment is the very last operation in the try block, we know that upon entering the catch block the variable will not have been assigned. However, formalizing the notion of "very last operation" would add significant complexity to the spec. Consider:

try {
    foo = bar();
    if (foo) {
        i = 4;
    } else {
        i = 7;
    }
}

Would that feature be useful? I don't think so, because a final variable must be assigned exactly once, not at most once. In your case, the variable would be unassigned if an Error is thrown. You may not care about that if the variable runs out of scope anyway, but such is not always the case (there could be another catch block catching the Error, in the same or a surrounding try statement). For instance, consider:

final int i;
try {
    try {
        i = foo();
    } catch (Exception e) {
        bar();
        i = 1;
    }
} catch (Throwable t) {
    i = 0;
}

That is correct, but wouldn't be if the call to bar() occured after assigning i (such as in the finally clause), or we use a try-with-resources statement with a resource whose close method throws an exception.

Accounting for that would add even more complexity to the spec.

Finally, there is a simple work around:

final int i = calculateIndex();

and

int calculateIndex() {
    try {
        // calculate it
        return calculatedIndex;
    } catch (Exception e) {
        return 0;
    }
}

that makes it obvious that i is assigned.

In short, I think that adding this feature would add significant complexity to the spec for little benefit.

6
  • 1. "Very last operation" rule is defined simply as "the last statement in try must be an assignment to the final variable." 2. Naturally, each catch-block would need to contain an assignment. This already has a precedent in the rules for assignment in if-else blocks. 3. The workaround isn't simple because it requires a whole new method, which means thinking up yet another "meaningful" name for an arbitrary piece of code. It also displaces the code, making the main flow of logic that much harder to follow. Jun 19, 2013 at 15:24
  • 1. That would be simple, but fail to catch obvious cases (I added an example for this to my answer). 2. Your proposed rule does not generalize to nested try statements (I added an example to my answer). One can fix it at the cost of additional complexity, or choose not to fix it, at the cost of limited usefulness. 3. I did not claim it to be the most elegant or beautiful solution. Still, if that's the biggest problem in a codebase, I'd consider myself blessed :-)
    – meriton
    Jun 19, 2013 at 18:29
  • In short, while this would be useful on occasion, I think if appropriate that this feature was not, and is not, given priority, because there are many conceivable improvements to Java that address a more pressing need.
    – meriton
    Jun 19, 2013 at 18:37
  • Thanks for the opinion, but sadly, it is quite off-topic in the context of this question. Jun 19, 2013 at 18:56
  • FWIW, I think your suggested approach would be the correct one. Try/Catch blocks like this example should be refactored and pushed down into the 'calculation' whenever possible - cleaner and probably correct in more situations. If the value being set in the handler is a "default" and the calculate method is called from multiple places, what happens when the default value needs to change?
    – JoeG
    Jul 3, 2013 at 19:32
3
1   final int i;
2   try { i = calculateIndex(); }
3   catch (Exception e) { 
4       i = 1; 
5   }

OP already remarks that at line 4 i may already have been assigned. For example through Thread.stop(), which is an asynchronous exception, see http://docs.oracle.com/javase/specs/jvms/se7/html/jvms-2.html#jvms-2.5

Now set a breakpoint at line 4 and you can observe the state of the variable i before 1 is assignd. So loosening the observed behaviour would go against the Java™ Virtual Machine Tool Interface

11
  • Ok, all asynchronous exception are of type Error (ThreadDeath and VirtualMachineError), afaik. My answer then only applies if Error is caught. Very subtle for a compiler to validate. Jun 20, 2013 at 9:52
  • Asynchronous or not, an exception causes the currently executed statement to complete abruptly. That is is formally how an exception appears in a Java program. Jun 20, 2013 at 10:33
  • Combined with the point given by @user1676075 your point gains strength: the write to the variable is not the last action performed in the try block, there may still be a goto which jumps over the exception handlers. BTW I tested my statement that ThreadDeath can't be caught and proved it false: it is caught just like any other exception, meaning that Thread#stop doesn't at all force the thread to stop. This comes as quite a surprise, and something I'll find useful in answering future SO questions! Jun 20, 2013 at 19:30
  • Can you provide a specific reference and/or quote from the JVMTI which backs your claim that such a breakpoint can be set and the value of the final variable observed? A related issue is, how does the tooling know that the variable is not assigned? Where is that information stored? Jun 20, 2013 at 19:46
  • I will answer my last question above myself: it is not stored anywhere; the tooling must simply know what variables are definitely assigned at a point in code and never show the current value of any other variables. Which brings us back to my earlier position: the accidental write to the variable would not be allowed to be shown by a debug tool. Jun 20, 2013 at 20:00
2

Browsing the javadoc, it seems no subclass of Exception could be thrown just after i is assigned. From a JLS theoretical perspective, it seems Error could be thrown just after i is assigned (e.g. VirtualMachineError).

Seems there's no JLS requirement for compiler to determine whether i could be previously set when catch block is reached, by distinguishing whether you're catching Exception or Error/Throwable, implying it's a weakness of JLS model.

Why not try the following? (have compiled & tested)

(Integer Wrapper Type + finally + "Elvis" operator to test whether null):

import myUtils.ExpressionUtil;
....
Integer i0 = null; 
final int i;
try { i0 = calculateIndex(); }   // method may return int - autoboxed to Integer!
catch (Exception e) {} 
finally { i = nvl(i0,1); }       


package myUtils;
class ExpressionUtil {
    // Custom-made, because shorthand Elvis operator left out of Java 7
    Integer nvl(Integer i0, Integer i1) { return (i0 == null) ? i1 : i0;}
}
12
  • 1
    Any exception can equally be thrown regardless of its type and any throws declaration. Checked exceptions are a compiler artifact only and easily foiled. Just google "sneaky throw". Unfortunately I don't see the point of your example. In finally you're using i0, which may obviously not have been assigned. Jun 18, 2013 at 9:18
  • Yes, know about the JVM-level trickery. Finally uses i0 only if it was successfully assigned (not-null). Otherwise it uses 1. Precisely what you wanted.
    – Glen Best
    Jun 18, 2013 at 9:35
  • It seems like you don't entirely understand the concept of local variable initialization. An uninitialized variable has no value and cannot be read. Anyway, what I want is for my example to be allowed by the compiler. Jun 18, 2013 at 9:43
  • Thanks. Was treating local vars like instance vars, coded v quickly :). Edited post to make i0 non-final, with default of null. Now compiled, tested, working. BTW: didn't you raise the Q because your example isn't allowed by the compiler? So I've given as close an alternative as I could create.
    – Glen Best
    Jun 18, 2013 at 10:19
  • I raised the question because I claim that my legitimate code is not allowed by JLS rules on strictly formal grounds, and I'm looking for an authoritative confirmation/rebuttal of my hypothesis. I am not looking for any working alternatives because I am aware of all my options. For example, I'd either make calculateIndex protect me from any exceptions or just make i non-final. Jun 18, 2013 at 10:33
2

I think there is one situation where this model act as life saver. Consider the code given below:

final Integer i;
try
{
    i = new Integer(10);----->(1)
}catch(Exception ex)
{
    i = new Integer(20);
}

Now Consider the line (1). Most of the JIT compilers creates object in following sequence(psuedo code):

mem = allocate();   //Allocate memory 
ctorInteger(instance);//Invoke constructor for Singleton passing instance.
i = mem;        //Make instance i non-null

But, some JIT compilers does out of order writes. And above steps is reordered as follows:

mem = allocate();   //Allocate memory 
i = mem;        //Make instance i non-null
ctorInteger(instance);  //Invoke constructor for Singleton passing instance.

Now suppose, the JIT performs out of order writes while creating the object in line (1). And suppose an exception is thrown while executing the constructor. In that case, the catch block will have i which is not null . If JVM doesn't follow this modal then in this case final variable is allowed to be assigned twice!!!

3
  • Which would be correct: The reference to the partially constructed object in the try block (that should not have been assigned) is overwritten by the correct value before anybody can read the incorrect value. Quoting the spec: "The memory model describes possible behaviors of a program. An implementation is free to produce any code it likes, as long as all resulting executions of a program produce a result that can be predicted by the memory model."
    – meriton
    Jun 19, 2013 at 6:07
  • @meriton Yes, you are right in what you are saying..But what I want to emphasize is that in this way the final variable goes through the process of initialization twice. Which is against the definition of final.
    – Vishal K
    Jun 19, 2013 at 6:24
  • @Vishalk As long as your code cannot observe the value being initialized twice, it is as good as if this didn't happen. Jun 19, 2013 at 15:17
2

But i may be assigned twice

    int i;
    try {
        i = calculateIndex();  // suppose func returns true
        System.out.println("i=" + i);
        throw new IOException();
    } catch (IOException e) {
        i = 1;
        System.out.println("i=" + i);
    }

output

i=0
i=1

and it means it cannot be final

5
  • I have constrained my case to just the last statement of try. Otherwise the question wouldn't make much sense. Jun 13, 2013 at 9:21
  • That's right, reaching catch block does not mean variable is not initialized. If you study JVMS, you'll know how exceptions are compiled and handled. May be this will clarify the question. To me javac's behavior is logical.
    – Mikhail
    Jun 19, 2013 at 6:51
  • @Noofiz Is your statement about Evgeniy's code or mine? In my code it does mean it is not initialized. Jun 19, 2013 at 15:28
  • Variable declared is not final -1
    – Chris
    Jun 19, 2013 at 18:08
  • @Chris Of course Evgeniy didn't declare his variable final---if he did, his code would not be legal Java. Plus, his point is quite clearly not about the finalness of i. Jun 19, 2013 at 18:59
2

EDITING RESPONSE BASED UPON QUESTIONS FROM OP

This is really in response to the comment:

All you have done is written up a clear-cut example of a straw man argument: you are vicariously introducing the tacit assumption that there must always be one and only one default value, valid for all call sites

I believe that we are approaching the entire question from opposite ends. It seems that you are looking at it from the bottom up - literally from the bytecode and going up to the Java. If this is not true, you are looking at it from the "code" compliance to the spec.

Approaching this from the opposite direction, from the "design" down, I see problems. I think it was M. Fowler who collected various "bad smells" into the book: "Refactoring: Improving the Design of Existing Code". Here (and probably many, many other places) the "Extract Method" refactoring is described.

Thus, if I imagine a made-up version of your code without the 'calculateIndex' method, I might have something like this:

public void someMethod() {
    final int i;
    try {
        int intermediateVal = 35;
        intermediateVal += 56;
        i = intermediateVal*3;
    } catch (Exception e) {
        // would like to be able to set i = 1 here;
    }
}

Now, the above COULD have been refactored as originally posted with a 'calculateIndex' method. However, if the 'Extract Method' Refactoring defined by Fowler is completely applied, then one gets this [note: dropping the 'e' is intentional to differentiate from your method.]

public void someMethod() {
    final int i =  calculateIndx();
}

private int calculateIndx() {
    try {
        int intermediateVal = 35;
        intermediateVal += 56;
        return intermediateVal*3;
    } catch (Exception e) {
        return 1;  // or other default values or other way of setting
    }
}

So from the 'design' perspective the problem is the code you have. Your 'calculateIndex' method does NOT calculate the index. It only does sometimes. The rest of the time, the exception handler does the calculation.

Furthermore, this refactoring is far more accommodating to changes. For instance, if you have to change what I assumed was the default value of '1' to a '2', no big deal. However, as pointed out by the OP reply quoted, one cannot assume that there is only one default value. If the logic to set this grows to be only slightly complex it could still easily reside in the encapsulated exception handler. However, at some point, it too may need to be refactored into it's own method. Both cases still allow the encapsulated method to perform it's function and truly calculate the index.

In summary, when I get here and look at what I believe is the correct code, then there is no compiler issue for discussion. (I am most certain you will not agree: that is fine, I just want to be clearer about my viewpoint.) As for compiler warnings that come up for incorrect code, those help me realize in the first place that something is wrong. In this case, that refactoring is needed.

6
  • Do you have anything to back your assertion about the "window" between the last statement in try having completed normally and the try block having exited? What exactly computation is happening within this window? BTW Java as a language does have support for the Maybe monad, there's nothing special to it. What it doesn't have is a standard library built around the concept. Jun 20, 2013 at 19:02
  • I am not a spec guru, so I can not quote you anything from there if that is ultimately what you need. However, I have done a lot of really real-time programming and even if only one instruction is "required" to be executed, that would open up a window for an interrupt such as I describe. We do know that Java has to at least do some cleanup of locally scoped variables when exiting a try/catch block. I believe you can even "see" this by stepping through line by line in the debugger.
    – JoeG
    Jun 21, 2013 at 14:35
  • Not line-by-line, this would need at least the bytecode level. In the meantime @user1676075 provided a specific example involving a goto which jumps over exception handlers. But all this is still not enough because a definitely unassigned variable may not be read, so even if it was written before reaching catch, its value could never be observed. On a higher level of description, it has simply not been assigned. Jun 21, 2013 at 14:49
  • BTW Java does not have to do the cleanup of variables exiting scope. There was even a question revolving around an OOME which resulted from the vars not being cleared. Jun 21, 2013 at 14:51
  • Finally read this again. Look at the very byte code @user1676075 posted. Any interrupt/exception that occurs on that Thread AFTER line 4 and BEFORE line 5 (i.e. a small, but real, window) will cause "i" to be set twice.
    – JoeG
    Jul 3, 2013 at 19:27
1

As per specs JLS hunting done by "djechlin", specs tells when is the variable definitely unassigned. So spec says that in those scenarios it is safe to allow the assignment.There can be scenarios other than the one mentioned in the specs in which case variable can still be unassigned and it will depend on compiler to make that intelligent decision if it can detect and allow an assignment.

Spec in no way mentions in the scenario specified by you, that compiler should flag an error. So it depends on compiler implementation of spec if it is intelligent enough to detect such scenarios.

Reference: Java Language Specification Definite Assignment section "16.2.15 try Statements"

3
  • This is not true. The compiler must strictly respect the regulations of definitely unassigned and definitely assigned. It must not allow assignment to a final variable which is not definitely unassigned. Jun 20, 2013 at 18:44
  • @Marko Topolnik: I agree that compiler must strictly respect JLS. However for the scenario you mentioned, "JLS Definite Assignment - try Statements" section does not make an either claim that "V is definitely assigned" or "V is definitely unassigned". JLS has not included your scenario at all and hence it is left up to the compiler implementation to optionally detect and handle such scenarios. Jun 21, 2013 at 21:24
  • No: definitely assigned is a precondition to allow reading of the variable; definitely unassigned is a precondition to allow writing to a final variable. Therefore a variable which is neither of the above, and is final, must not be allowed to be either read or written. Jun 21, 2013 at 22:38
1

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]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.