0

我是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(); 
    } 

NullPointerException我的问题是:程序可能会在函数中抛出 a nullPrintStream(),我们不需要在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[]) {

    }
}

就像我想的那样,我收到了一个错误Unhandled exception type Exception,但是为什么System.out不使用 Exception 就可以了NullPointerException

4

3 回答 3

3

Java 有一个特殊的异常类,称为RuntimeExceptions。它们都扩展了RuntimeException对象,而对象又扩展了Exception对象。RuntimeException(与常规异常相反)的特殊之处在于它不需要显式抛出。有几种不同的例外情况属于此类别,例如IllegalArgumentExceptionIllegalStateException...

在编码时使用 RTE 的优势在于,您无需使用大量 try/catch/throws 语句来覆盖您的代码,尤其是在异常极少且不太可能发生的情况下。此外,如果你有一个捕获 RTE 的通用机制,这也将有助于确保你的应用程序干净地处理预期条件。

话虽如此,RTE 可能更难处理,因为从签名中看不出特定类或方法会抛出那种类型的异常。因此,它们对于 API 来说并不总是一个好主意,除非它们有很好的文档记录。

NullPointerException是 RuntimeException,因此不需要在方法签名中显式声明。

于 2012-01-29T05:56:49.047 回答
1

如果我在 private static int throwException() 中坚持 throw Exception(),我应该如何修改 public static final int aTestObject = throwException();

您可能需要初始化静态块中的值并在那里捕获异常。

public static final int aTestObject;
static {
  try {
    aTestObject = throwException();  <==Here i got an error
  } catch (Exception e) {
    throw new AssertionError(e);
  }
}
于 2012-01-29T08:58:30.963 回答
1

NullPointerExceptionRuntimeException- 它不需要被显式捕获。

如果你让你的方法这样做,它不会在编译时爆炸:

private static int throwException() throws Exception{
    int m = 1;
    if(m == 0) {
        throw new RuntimeException();
    }
    return 0;
}
于 2012-01-29T05:44:27.170 回答