为什么在Java中,在try块中定义的变量不能在catch或finally块中使用?
Java中的类将包含三种变量,即静态(类)变量、实例变量和局部变量。
实例变量 − 这些变量属于类的实例(对象)。它们在类中声明,但在方法之外。当类被实例化时,它们会被初始化。可以从该特定类的任何方法、构造函数或块中访问它们。
类/静态变量 − 类/静态变量属于类,就像实例变量一样,它们在类中声明,在任何方法之外,但使用static关键字。
它们在编译时可用,你可以在实例化类之前/无需实例化类即可访问它们,在整个类中只有一个静态字段的副本可用,即静态字段的值在所有对象中都相同。可以使用static关键字定义静态字段。
局部变量 − 这些变量属于并在方法/块/构造函数中声明/定义。这些变量的作用域位于方法(或块或构造函数)内,并在其执行后被销毁。
try块中的变量
因此,如果在try块中声明一个变量(在任何块中都是如此),它将是该特定块的局部变量,变量的生命周期在块执行后结束。因此,无法访问在块中声明的任何变量,在块外部。
示例
在下面的示例中,我们声明了一个名为result的变量,并尝试在finally块中访问它,编译时会产生编译时错误。
import java.util.Arrays;
import java.util.Scanner;
public class ExceptionExample {
public static void main(String [] args) {
Scanner sc = new Scanner(System.in);
int[] arr = {10, 20, 30, 2, 0, 8};
System.out.println("Array: "+Arrays.toString(arr));
System.out.println("Choose numerator and denominator(not 0) from this array (enter positions 0 to 5)");
int a = sc.nextInt();
int b = sc.nextInt();
try {
int result = (arr[a])/(arr[b]);
}catch(Exception e) {
System.out.println("exception occured");
} finally {
System.out.println("This is finally block");
System.out.println("Result of "+arr[a]+"/"+arr[b]+": "+result);
}
}
}输出
ExceptionExample.java:21: error: cannot find symbol
System.out.println("Result of "+arr[a]+"/"+arr[b]+": "+result);
^
symbol: variable result
location: class ExceptionExample
1 error
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP