父类方法抛出的异常,子类重写时怎么处理?

前言

重写(注意与重载的区别)是面向对象语言实现多态特性的重要知识点,与其它知识点结合一起使用过程中,会产生一些让人疑惑的点,这篇文章是为了演示与解释重写与异常两个知识点碰撞时产生的问题。这里先给出结论:子类在重写父类带有异常的方法时,可以自行决定是否抛出异常,但如果要抛出异常,那么抛出的异常的层级一定不能高于父类方法抛出的异常所处的层级。

测试

测试1

父类抛出异常,子类不抛出异常

public class ExceptionDemo {
	private static class Parent {
		public String echo(String name) throws Throwable {
			return String.format("hello, %s from the Parent echo function", name);
		}
	}

	private static class Child extends Parent {
		@Override
		public String echo(String name) {
			return String.format("hello, %s from the Child echo function", name);
		}
	}

	public static void main(String[] args) {
		Child child = new Child();
		System.out.println(child.echo("eagle"));
	}
}

运行结果:程序正常运行

测试二

父类抛出异常,子类也抛出异常

public class ExceptionDemo {
	private static class Parent {
		public String echo(String name) throws Throwable {
			return String.format("hello, %s from the Parent echo function", name);
		}
	}

	private static class Child extends Parent {
		@Override
		public String echo(String name) throws Throwable {
			return String.format("hello, %s from the Child echo function", name);
		}
	}

	public static void main(String[] args) {
		Child child = new Child();
		System.out.println(child.echo("eagle"));
	}
}

运行结果:程序正常运行

测试三

父类不抛出异常,子类抛出异常

public class ExceptionDemo {
	private static class Parent {
		public String echo(String name) {
			return String.format("hello, %s from the Parent echo function", name);
		}
	}

	private static class Child extends Parent {
		@Override
		public String echo(String name) {
			return String.format("hello, %s from the Child echo function", name);
		}
	}

	public static void main(String[] args) {
		Child child = new Child();
		System.out.println(child.echo("eagle"));
	}
}

运行结果:程序编译不通过。抛出的错误信息为:

ExceptionDemo.java:24: 错误: Child中的echo(String)无法覆盖Parent中的echo(String)
public String echo(String name) throws Throwable {
^
被覆盖的方法未抛出Throwable

解释

因为面向对象语言的多态性,经常出现下面类型的程序调用方式

Parent obj = new Child();
try{
	obj.echo("eagle");
} catch(Throwable t) {
	// 异常逻辑处理
}

代码中是按照 Parent 中对 echo 方法的定义来捕获异常的,但程序在JVM运行过程中,执行的确是 Child 中定义的 echo 方法,如果该方法抛出的异常的层级高于Parent 中的 echo 方法的异常所处的层级,那么该段程序将无法处理,从而与多态特性产生矛盾。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值