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

前言

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

测试

测试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 方法的异常所处的层级,那么该段程序将无法处理,从而与多态特性产生矛盾。

经验分享 程序员 微信小程序 职场和发展