【问题标题】:Why we must handle exception for method not throwing exceptions? [duplicate]为什么我们必须为不抛出异常的方法处理异常? [复制]
【发布时间】:2013-06-18 13:45:46
【问题描述】:

给定

public class ToBeTestHandleException{

static class A {
    void process() throws Exception {
        throw new Exception();
    }
  }

static class B extends A {
    void process() {
        System.out.println("B ");
    }
   }



public static void main(String[] args) {
    A a = new B();
    a.process();
   }

  }

为什么要在 (a.process()) 行处理异常?. B 类的方法 process 根本不抛出异常? PS:这是一个 SCJP 问题。

【问题讨论】:

    标签: java exception methods handle scjp


    【解决方案1】:

    您已将B 实例分配给A 类型的变量。由于A.process() 抛出异常,您的代码需要处理这种可能性。

    假设您将实例传递给另一个接受 As 的方法:

    public void doSomething(A a) {
      a.process; // <--- we don't know this is a B, so you are forced to 
                 //      catch the exception
    }
    

    【讨论】:

    • 干得好 Duncan Jones。非常感谢您的回答。这绝对是正确的。再次感谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-04-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-17
    • 1970-01-01
    • 2021-11-12
    相关资源
    最近更新 更多