java 异常声明,Java声明“抛出异常”默认?

本文探讨了Java中子类重写父类方法时异常处理的规则。子类重写方法必须抛出与父类相同或者更具体的异常,不允许抛出父类未声明的检查异常。允许子类不抛异常,或者抛出运行时异常。博客内容涉及到Java异常分类、重写方法的限制以及实例示例。
摘要由CSDN通过智能技术生成

Consider following classes:

class X

{

public void met()

{

}

}

and

class Y extends X

{

public void met() throws NullPointerException

{

throw new NullPointerException();

}

}

I understand that the overriding method in the subclass, has to throw either the same or a subclass of the exception thrown in the overridden method.

Do Java methods always throw at least an exception of the type Exception?

...In other words the compiler adds throws Exception

So the class X would look like this

class X {

public void met() throws Exception {

}

}

I want to clarify that I am not mistaken about the fact that the default exception handler Exception is always added.

Related questions:

解决方案

There are two types of Exceptions: checked Exceptions (like ParseExceptionwhen parsing text) and unchecked Exceptions (like NullPointerException).

Checked Exceptions must be declared in the method signature. Unchecked Exceptions may be declared in the method signature.

When overriding methods (from an interface or a super class) you only have to specify the exceptions, that you are throwing in your implementation. You cannot declare to throw checked exceptions in an implementation that are not allowed in the overridden method.

This is allowed:

class X { void someMethod() }

class Y extends X { @Override void someMethod() throws UncheckedException }

This is not allowed:

class X { void someMethod() }

class Y extends X { @Override void someMethod() throws CheckedException }

This is also allowed:

class X { void someMethod() throws CheckException }

class Y extends X { @Override void someMethod() }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值