问题
In the below java program even though the member "x" is defined outside the try block, it is accessible inside the try block. In case of "y", it is defined inside try block. But it is not accessible outside the try block. Why it is so?
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);
}
}
output is:
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)
回答1:
Any {}
block defines a scope in Java. So any variable (such as y
) declared inside the try block is only accessible inside the try block.
x
is declared in the outer block that contains your try block (that's the block of your entire main
method), so it's accessible inside your try block.
回答2:
Each local variable (a variable of a method) in Java has a scope delimited by a {}
block in which it is declared: within it the variable is accessible, outside it the variable is not accessible. In other words, the variable you declared only exists in the {}
where it was declared.
In your example the scope of the variable x
is within the method itself, while the scope of y
is within the try
block:
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
To assure which is the scope of a local variable, you have consider the first {
immediately before the declaration of the variable as the begin of the scope and the }
which closes the opening brace as the end -- note that the latter is not necessarily the first closing brace as there could be other nested levels of {}
block after the declaration of the variable (in your example x
has nested {}
blocks in which the variable is still accessible because the closing brace }
is the one that closes the main method).
来源:https://stackoverflow.com/questions/32805813/what-is-the-scope-of-a-variable-defined-inside-java-try-block-why-it-is-not-acc