java try块中定义的变量的范围是什么?为什么在try块之外无法访问它?

Sha*_*ane 0 java try-catch

在下面的java程序中,即使成员"x"在try块之外定义,它也可以在try块中访问.在"y"的情况下,它在try块内定义.但是在try块之外无法访问它.为什么会这样?

package com.shan.interfaceabstractdemo;

public class ExceptionDemo {
    public static void main(String[] args) {
        int x = 10;
        try {
            System.out.println("The value of x is:" + x);
            int y = 20;
        } catch (Exception e) {
            System.out.println(e);
        }
        System.out.println("The value of y is:" + y);
    }
}
Run Code Online (Sandbox Code Playgroud)

输出是:

Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
y cannot be resolved to a variable

at com.felight.interfaceabstractdemo.ExceptionDemo.main(ExceptionDemo.java:12)
Run Code Online (Sandbox Code Playgroud)

Era*_*ran 5

任何{}块都在Java中定义范围.因此,y在try块内声明的任何变量(例如)只能在try块内访问.

x在包含try块的外部块中声明(这是整个main方法的块),因此可以在try块中访问它.