【发布时间】:2012-01-29 05:41:45
【问题描述】:
我是java新手,为了弄清楚“System.out”,我阅读了相关的java源代码,然后发现了一些我无法理解的东西。 首先是“System.out”的源代码:
public final static PrintStream out = nullPrintStream();
然后我去了nullPrintStream
private static PrintStream nullPrintStream() throws NullPointerException {
if (currentTimeMillis() > 0) {
return null;
}
throw new NullPointerException();
}
我的问题是:程序可能会在函数nullPrintStream()中抛出一个NullPointerException,我们不需要在public final static PrintStream out = nullPrintStream();中捕获异常吗?为了弄清楚这一点,我在 Eclipse 中编写了一些测试代码如下:
package MainPackage;
public class Src {
private static int throwException() throws Exception{
int m = 1;
if(m == 0) {
throw new Exception();
}
return 0;
}
public static final int aTestObject = throwException(); <==Here i got an error
public static void main(String args[]) {
}
}
就像我想的那样,我得到了一个错误未处理的异常类型 Exception,但是为什么 System.out 不使用 NullPointerException 就可以了?
【问题讨论】: