【问题标题】:"unhandled checked exception as a thrown exception" in JavaJava中的“未处理的检查异常作为抛出的异常”
【发布时间】:2012-06-19 16:55:30
【问题描述】:

我正在学习 SCJP 6 学习指南 Exam_310-065 的第 5 章,并且在 异常声明和公共接口部分它说

“每个方法必须要么通过提供一个 catch 子句来处理所有已检查的异常,要么将每个未处理的已检查异常列为抛出 例外。”

我们如何将每个未处理的已检查异常列为抛出的异常,它在代码中的外观如何?谢谢。

【问题讨论】:

    标签: java


    【解决方案1】:

    看起来像这样:

    public void foo() throws SomeCheckedException, AnotherCheckedException
    {
        // This method would declare it in *its* throws clause
        methodWhichThrowsSomeCheckedException();
    
        if (someCondition)
        {
            // This time we're throwing the exception directly
            throw new AnotherCheckedException();
        }
    }
    

    更多信息请参见section 8.4.6 in the JLS

    【讨论】:

      【解决方案2】:

      例如,如果您有:

      public void doSomething() throws SomeException { 
          ... 
          throw new SomeException();
      } 
      

      如果你想调用doSomething,你必须要么catch异常,要么声明使用它的方法也容易抛出SomeException,因此在调用堆栈中进一步传播它:

      public void doSomethingElse() throws SomeException { 
          doSomething();
      }
      

      或者

      public void doSomethingElse() { 
          try { 
              doSomething();
          }
          catch (SomeException) { 
              // Error handling
          }
      }
      

      考虑到RuntimeExceptions 不是检查异常,因此它们是该规则的一个例外。

      【讨论】:

      • 太棒了!谢谢各位先生的解释。
      猜你喜欢
      • 1970-01-01
      • 2011-10-10
      • 2013-06-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-03
      • 2013-07-24
      • 2013-10-15
      相关资源
      最近更新 更多