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

What is the scope of a variable defined inside java try block? Why it is not accessible outside of the try block?

在下面的 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);
    }
}

输出为:

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)

任何 {} 块在 Java 中定义范围。所以在 try 块内声明的任何变量(例如 y)只能在 try 块内访问。

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

Java 中的每个局部变量(方法的变量)都有一个由 {} 块分隔的范围,在该块中声明它:在它内部变量是可访问的,在它外部变量不可访问。换句话说,你声明的变量只存在于声明它的{}中。

在您的示例中,变量 x 的范围在方法本身内,而 y 的范围在 try 块内:

public static void main(String[] args) { 
    // here x scope begins
    int x = 10;
    try { // here y scope begins
        System.out.println("The value of x is:" + x);
        int y = 20;
    } // here y scope ends
       catch (Exception e) {
        System.out.println(e);
    }
    System.out.println("The value of y is:" + y);
}
// here x scope ends

为了确定哪个是局部变量的范围,您已经考虑紧接变量声明之前的第一个 { 作为范围的开始,而 } 关闭开口大括号作为结束 - 请注意,后者不一定是第一个右大括号,因为在变量声明之后可能还有 {} 块的其他嵌套级别(在您的示例中 x 嵌套了 {} 块,其中变量仍然可以访问,因为右括号 } 是关闭 main 方法的那个)。