标签:style color io os ar java strong 数据 sp
十、异常的应用
import java.util.Random; import javax.rmi.CORBA.Stub; /* *老师用电脑上课 *用面向对象思考问题 *问题设计两个对象 *老师,电脑 * *可能发生的问题: *电脑蓝屏、电脑冒烟 */ class Lan extends Exception//蓝屏 { Lan(String problem) { super(problem); } } class Fir extends Exception//冒烟 { Fir(String problem) { super(problem); } } class No extends Exception { No(String problem) { super(problem); } } class Computer {//定义一个电脑运行的状态 private int stu = 3; //stu为1正常,2是蓝屏,3是冒烟 //stu = Random()%2+1; public void run()throws Lan,Fir { switch (stu) { case 2: throw new Lan("Computer is Lan!!!"); //此处就不用break了,因为已经抛出了 case 3: throw new Fir("Computer is Fir!!!"); case 1: System.out.println("Computer is running"); break; } } public void rest()//电脑重启 { stu = 0; System.out.println("Computer is rest"); } } class Teacher { private String name = null; private Computer C; Teacher(String name) { this.name = name; C = new Computer(); } public void lesson()throws Fir,No { try { C.run(); System.out.println(name+" teacher is teaching"); } catch(Lan a) { System.out.println(a.toString());//打印信息 C.rest(); lesson(); } catch(Fir b) { System.out.println(b.toString());//打印信息 test(); //能处理的已经处理了,处理不了的继续向外抛 //找人,对电脑进行维修,并告知学校并带原因,不告知,就是异常异常 throw new No("课时无法进行,"+b.getMessage()); } } public void test()//做练习 { System.out.println("student is exciesing"); } } public class Main { public static void main(String[] args) { Teacher B = new Teacher("BLF2"); try { B.lesson(); } catch (Fir e) { System.out.println("....."); } catch (No e) { System.out.println(e.toString()); } finally {//无论课上发生什么,但是还是会下课 System.out.println("到点下课"); } } }
十一、异常的注意事项
(1).子类在覆盖父类方法时,父类的方法如果抛出了异常,那么子类的方法只能抛出子类的异常或者该异常的子类(见下述代码)
(2).如果父类抛出多个异常,那么子类只能抛出父类异常的子集
简单说:子类覆盖父类只能抛出父类的异常或者父类异常的子类或者子集
注意:如果父类的方法没有抛出异常,那么子类的覆盖时绝对不能抛
下述代码解释注意事项(1)
class A extends Exception {} class B extends A {} class C extends Exception {} class FU { void show()throws A { } } class Test { void method(FU f) { try { f.show(); } catch (A a) { } } } class ZI extends FU { void show()throws A,B //也可以不抛,但是不可以抛出其他异常 {} } public class Main { public static void main(String[] args) { Test t = new Test(); t.method(new ZI());//用多态就可以解释为什么不能抛其他的异常 } }
interface in { abstract void show(); } class BB implements in { public void show()//throws Exception,因为父类没有出现异常,子类就不能抛 { //如果真的出现异常,那么只能try,不能抛 } }
标签:style color io os ar java strong 数据 sp
原文地址:http://blog.csdn.net/wjw0130/article/details/39652621