In all the weeks, when the Java neutron class overrides the parent class method, if the parent throws an exception, the subclass must also throw the parent class's exception or subclass of the exception.
The following code is used to demonstrate this conclusion:
package cn.itcast.exception;//The following defines three custom exception classes, the relationships between them are as follows:/*exception|--aexception|--bexception|--cexception*/ Class aexception extends exception{public aexception (string msg) {super (MSG);}} Class bexception extends aexception{public bexception (string msg) {super (MSG);}} Class cexception extends exception{public cexception (string msg) {super (MSG);}} Test class Class test{public void function (fu f) {try {f.show ();} catch (aexception e) {system.out.println (e.tostring ());}}} Define a parent class and define a show method to throw a exception class fu{public void show () throws aexception{ System.out.println ("I am father"); Throw new aexception ("Aeception by fu");}} Define subclass override parent class Show () method Class zi extends fu{public void show () throws bexception{ System.out.println ("I am son"); Throw new bexception ("Aexception by zi");}} PubliC class exceptiondemo {public static void main (String[] args) {// todo auto-generated method stubtest t = new test (); T.function (new zi ());}}
In the above code, the parameter of the function that tests the class test is the parent class Fu, which calls the show () method referenced by F, and if it catches an exception, it should capture the exception of the Fu's Show method or its parent class, so that it does not violate the polymorphic characteristics.
However, when the parameters of the function are passed in, the Zi type object of Fu is transferred, and the polymorphism is used. F.show () calls the show method of the subclass, and if the show method of the subclass throws an exception or its subclass of the show () method of the non-Fu class, it will inevitably break the polymorphic feature.
This article is from the "line of the World" blog, please be sure to keep this source http://4259297.blog.51cto.com/4249297/1656639
The idea of Java programming-contradiction