java try块中定义的变量的作用域是什么?为什么在try块之外无法访问它?
在下面的java程序中,即使成员“x”是在try块外部定义的,也可以在try块内部访问它。如果是“y”,则在try块中定义。但在try块之外无法访问它。为什么会这样java try块中定义的变量的作用域是什么?为什么在try块之外无法访问它?,java,try-catch,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
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中的作用域。因此,在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
为确保哪一个是局部变量的范围,在变量声明之前,首先考虑第一个<代码> {< /C> >范围和<代码> }。将开始大括号作为结束符关闭——请注意,后一个大括号不一定是第一个结束大括号,因为在变量声明之后可能有其他嵌套级别的
{}
块(在您的示例中x
嵌套了{}
块,在该块中变量仍然可以访问,因为右大括号}
是关闭主方法的大括号。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
为确保哪一个是局部变量的范围,在变量声明之前,首先考虑第一个<代码> {< /C> >范围和<代码> }。将开始大括号作为结束符关闭——请注意,后一个大括号不一定是第一个结束大括号,因为在变量声明之后可能有其他嵌套级别的
{}
块(在您的示例中x
嵌套了{}
块,在该块中变量仍然可以访问,因为关闭大括号(}
是关闭主方法的大括号)