【问题标题】:Can we throw Parent type exception in the method if we written throws child type exception in the method signature?如果我们在方法签名中写了 throws child 类型异常,我们可以在方法中抛出 Parent 类型异常吗?
【发布时间】:2019-07-30 10:03:40
【问题描述】:
public void foo1() throws OException
{
    try {

    } catch(Exception e) {
        throw e;
    }
}

OException 扩展异常

OException 是第三方提供的 API 类

我在 throw e 语句的 catch 块中遇到编译错误

未处理的异常类型异常

这是因为我不能像我写的方法签名那样抛出 Parent 类型异常 throws OException 吗?

我可以通过以下两种方式解决这个编译错误:-

  • 如果我在方法签名中抛出异常而不是 OException
  • 如果我在 catch 块中抛出 OException 而不是父类型 Exception e

我的一个朋友在他的工作区中打开了相同的代码,并且没有给他任何复杂的错误,所以我对这里到底发生了什么感到困惑。

有人能解释一下吗?

【问题讨论】:

  • 理想情况下,您应该能够做到这一点。尝试检查包名称或重新启动 IDE。
  • @GurwinderSingh aleady 做了
  • 嗯,不,你不能,编译器已经告诉你了。不清楚你为什么要问。
  • @user207421 我问这个问题是因为我的朋友在我收到此编译错误时能够编译和运行相同的代码
  • 删除签名中的括号。将 thows OException() 更改为 throws OException

标签: java exception


【解决方案1】:

Exception 是已检查的异常类型。这意味着您必须捕获它(使用try { ... } catch(Exception ex) { ... } 或在使用throws 的方法中声明它。

由于Exception 类在异常层次结构中高于OException,因此您必须将throws OException 更改为throws Exception

如果捕获和重新抛出的异常类型是OException,那么throws 异常声明就可以了。

【讨论】:

    猜你喜欢
    • 2015-12-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-22
    • 2011-03-22
    • 2014-07-29
    • 2017-01-04
    • 1970-01-01
    相关资源
    最近更新 更多