r/javahelp • • Sep 19 '24

A try-catch block breaks final variable declaration. Is this a compiler bug?

UPDATE: The correct answer to this question is https://mail.openjdk.org/pipermail/amber-dev/2024-July/008871.html

As others have noted, the Java compiler seems to dislike mixing try-catch blocks with final (or effectively final) variables:

Given this strawman example

public class Test
{
  public static void main(String[] args)
  {
   int x;
   try
   {
    x = Integer.parseInt("42");
   }
   catch (NumberFormatException e)
   {
    x = 42;
   }
   Runnable runnable = () -> System.out.println(x);  
  }
}

The compiler complains:

Variable used in lambda expression should be final or effectively final

If you replace int x with final int x the compiler complains Variable 'x' might already have been assigned to.

In both cases, I believe the compiler is factually incorrect. If you encasulate the try-block in a method, the error goes away:

public class Test
{
  public static void main(String[] args)
  {
   int x = 
foo
();
   Runnable runnable = () -> System.
out
.println(x);
  }

  public static int foo()
  {
   try
   {
    return Integer.
parseInt
("42");
   }
   catch (NumberFormatException e)
   {
    return 42;
   }
  }
}

Am I missing something here? Does something at the bytecode level prevent the variable from being effectively final? Or is this a compiler bug?

3 Upvotes

67 comments sorted by

View all comments

Show parent comments

0

u/VirtualAgentsAreDumb Sep 21 '24

People will very frequently talk about what the compiler is thinking and what the compiler knows and other similar personifications when helping people out. This is never based on perfect knowledge of the full code of the compiler.

Naturally. But this discussion is about the reasons behind certain behavior of the compiler, with the main argument being that the compiler theoretically can do this.

From that perspective, saying that the compiler “doesn’t know” is effectively an argument that the compiler can’t know. We are discussing the potential, not the current state. The current state of the compiler is utterly irrelevant here. You should never answer a reasonable “why?” question with “that’s just how it is”.