【问题标题】:needn't to catch the exception in the realization of System.out?在System.out的实现中不需要捕获异常吗?
【发布时间】: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 就可以了?

【问题讨论】:

    标签: java exception system out


    【解决方案1】:

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

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

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

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

    【讨论】:

      【解决方案2】:

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

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

      private static int throwException() throws Exception{
          int m = 1;
          if(m == 0) {
              throw new RuntimeException();
          }
          return 0;
      }
      

      【讨论】:

      • 谢谢,我明白了。但是我还有一个问题:如果我坚持在private static int throwException()中抛出Exception(),我应该如何修改public static final int aTestObject = throwException();
      • 见彼得劳里的回答。如果您需要检查异常,请在此处使用他的静态初始化程序。当然,你如何处理它取决于你,他选择了 AssertionError 这是一个明智的选择 - 很难从一个没有正确初始化的类中恢复!
      【解决方案3】:

      如果我在 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-11-02
        • 2015-02-13
        • 1970-01-01
        • 1970-01-01
        • 2011-10-07
        • 2013-11-14
        • 2023-04-10
        • 2011-09-16
        • 1970-01-01
        相关资源
        最近更新 更多