老师用电脑上课,出现两种问题,电脑蓝屏,电脑冒烟。
名词提炼法:毕老师一个类,有上课功能 电脑一个类,有运行和重启功能 每个问题一个类,封装成对象。
其中,电脑炸了并不是老师的问题,抛给谁都无法解决,
但是,电脑炸了会导致老师无法上课,这就转化成了老师的问题。需要再用一个问题类来描述。
class Crash extends Exception
{
Crash(String message)
{
super(message);
}
}
class Boom extends Exception
{
Boom (String msg)
{
super(msg);
}
}
class CannotContinue extends Exception
{
CannotContinue(String msg)
{
super(msg);
}
}
class Computer
{
private int state = 3;
public void run()throws Crash,Boom
{
if (state==2)
throw new Crash("the computer need a reset");
if (state==3)
throw new Boom("the computer is gg ,please fuck it ");
System.out.println(" the computer is running");
}
public void reset()
{
state = 1;
System.out.println(" this is reseting ");
}
}
class Teacher
{
private String name;
private Computer pc;
Teacher (String name)
{
this.name = name;
pc = new Computer();
}
public void prelect()throws CannotContinue
{
try
{
pc.run();
}
catch(Crash e)
{
pc.reset();
}
catch(Boom e)
{
test();
throw new CannotContinue("the tool is gg and the course cannot continue " +e.getMessage());
//test(); //报错,因为这句话是绝对执行不到的,throw单独存在和return效果是一样的,下面语句都不执行
}
System.out.println(" the teacher is prelecting");
}
public void test()
{
System.out.println("do something interesting~~~");
}
}
class TestException
{
public static void main(String[] args)
{
Teacher bi = new Teacher("bi");
try
{
bi.prelect();
}
catch(CannotContinue e)
{
System.out.println(e.toString());
System.out.println("change another computer immediately");
}
}
}
finally 中存放的是一定会执行的代码。通常用于关闭资源。
在catch(A e)
{
throw new B();
}
一种分层思想,把问题封装起来,抛回后给个反馈。
通常,一个throw后必须对应一个catch.
catch 是用于解决问题,如果没有catch说明问题没有被解决,如果该异常是编译时异常就必须声明。
异常在重写父类方法时的体现 :
1、子类在覆盖父类时,子类只能抛父类抛过的异常或者父类异常的子异常,不能抛父类没有的异常。换言之,子类不能比父类问题还麻烦。
具体原理是,早期代码无法处理后期代码的异常。
2、如果父类方法抛出多个异常,子类在覆盖父类方法时,只能抛出父类异常子集的异常。
3、如果父类方法中没有异常抛出,子类在覆盖方法时也不可以抛出异常。但子类如果确实有异常,就只能try catch处理而不能抛出。