java编译中出现意外的错误顺序

前端之家收集整理的这篇文章主要介绍了java编译中出现意外的错误顺序前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
在线解决挑战时,我发现了 java的以下行为,我发现它有点奇怪.我从以下大纲编写程序开始:
import java.io.*;

class WeirdJava
{
    public static void main (String[] args) 
    {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String input = br.readLine();
        HashMap<Integer,Integer> map = new HashMap<Integer,Integer>();
        System.out.println("Weird Java");
    }
}

请注意,在上面的程序中,有两个错误

>我没有处理BufferedReader可能抛出的异常.
>我没有导入包含HashMap的标准util库.

现在,当我尝试编译上面的程序时,java编译器给出了它无法找到符号HashMap的错误.请注意,涉及HashMap的声明位于BufferedReader之后.接下来,我将以下import语句添加到程序中:

import java.util.HashMap;

当我再次编译程序时,这次编译器显示错误

unreported exception IOException; must be caught or declared to be
thrown

我的问题:

>为什么在先前的编译尝试中没有抛出此错误
>编译错误发生的顺序似乎并不自然.在这个例程中,编译器设计原则是什么?

解决方法

它只是编译器检查源的顺序.特别是,在检查调用可以引发已检查异常的方法代码之前,编译器会检查导入并解析它们.

如果你用-verbose运行javac,你会注意到编译器加载了导入的类,在本例中是BufferedReader和InputStreamReader,然后它加载了像Object和String这样的公共API类:

[loading ZipFileIndexFileObject[C:\Dev\Java\jdk1.7.0_75\lib\ct.sym(Meta-INF/sym/rt.jar/java/io/BufferedReader.class)]]
[loading ZipFileIndexFileObject[C:\Dev\Java\jdk1.7.0_75\lib\ct.sym(Meta-INF/sym/rt.jar/java/io/InputStreamReader.class)]
]    
[loading ZipFileIndexFileObject[C:\Dev\Java\jdk1.7.0_75\lib\ct.sym(Meta-INF/sym/rt.jar/java/lang/Object.class)]]
[loading ZipFileIndexFileObject[C:\Dev\Java\jdk1.7.0_75\lib\ct.sym(Meta-INF/sym/rt.jar/java/lang/String.class)]]
[checking test.Test]
[loading ZipFileIndexFileObject[C:\Dev\Java\jdk1.7.0_75\lib\ct.sym(Meta-INF/sym/rt.jar/java/lang/AutoCloseable.class)]]
[loading ZipFileIndexFileObject[C:\Dev\Java\jdk1.7.0_75\lib\ct.sym(Meta-INF/sym/rt.jar/java/lang/System.class)]]
[loading ZipFileIndexFileObject[C:\Dev\Java\jdk1.7.0_75\lib\ct.sym(Meta-INF/sym/rt.jar/java/io/InputStream.class)]]
[loading ZipFileIndexFileObject[C:\Dev\Java\jdk1.7.0_75\lib\ct.sym(Meta-INF/sym/rt.jar/java/io/Reader.class)]]
Test.java:11: error: cannot find symbol
    HashMap<Integer,Integer>();

通过查看this link中的概述,加载已使用的类本身是第一阶段编译的一部分,称为“Parse and Enter”:

Each tree is passed to Enter,which enters symbols for all the definitions encountered into the symbols. This has to done before analysis of trees which might reference those symbols. The output from this phase is a To Do list,containing trees that need to be analyzed and have class files generated.

猜你在找的Java相关文章