-1
public class Test {

    public static void main(String[] args) {
        
        int a;
        // for( a=0; a<5; a++ ){}
        try {
            a=10;
        } catch (Exception e) {
            //TODO: handle exception
        }
        System.out.println(a);
    }
}

In the above code, initialization to var a by for loop persists while printing it, but not with try block.

5
  • Are you getting a compile error variable a might not have been initialized? Commented May 12, 2022 at 9:30
  • 1
    You have created a path through your code in which a might not be initialised. Commented May 12, 2022 at 9:31
  • Note: you really want to read minimal reproducible example and enhance your question accordingly. Commented May 12, 2022 at 9:31
  • 1
    @JoSSte An int cannot have a NullPointerException as it cannot be null. As far as the compile is concerned, there is a code-path (the catch block) that doesn't initialize a, so it simply disallows it. Commented May 12, 2022 at 10:03
  • good point - couldn't edit it - so removed my comment instead Commented May 12, 2022 at 10:26

1 Answer 1

2

The java compiler doesn't know what is going to happen in the try block.

The whole point of the try/catch is: there is some code that might execute fine, or might not. Therefore the assignment to a inside the try block is not guaranteed to happen, therefore the following read access to a might find it as (still) not initialized.

The real answer: there are many situations where a human reader can see "there is no problem here". But the java compiler fails to recognize that special case. Of course, one could write a compiler that detects "a is assigned a value, and that code will never throw an exception". But the java compiler isn't written that way. That is all there is to this.

Sign up to request clarification or add additional context in comments.

1 Comment

Change "meaningless" to "not guaranteed", and "invalid" to "uninitialized"?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.