最近自学到自定义异常这里,头就有点大了,毕老师视频里那个长长的例子认真的体会并写了两遍,感觉有些问题还是似懂非懂。结合贴出来的长例子,主要有以下问题:
1、Teacher类中,方法prelect()中直接引用Computer()对象中的方法,假如不是在构造函数时创建的对象new Computer(),而是在该类中的其它方法里创建,还能否在prelect()里引用,为什么?
2、异常抛出与异常处理之间的具体处理机制是什么?
比如在以下程序中:
当Computer类中的state为3时,就执行if(state==3),从这里一直到相应的catch()发生(两个catch:Teacher里边的和main里边的),应该怎样去理解中间的这个过程?
知道程序长了看起来有点不爽,先在此感谢了
class LanPingException extends Exception
{
LanPingException(String message)
{
super(message);
}
}
class MaoYanException extends Exception
{
MaoYanException(String message)
{
super(message);
}
}
class NoPlanException extends Exception
{
NoPlanException(String message)
{
super(message);
}
}
//---------------------------------------
class Computer
{
private int state = 3;
public void run() throws LanPingException, MaoYanException
{
if(state==2)
throw new LanPingException("蓝屏了!");
if(state==3)
throw new MaoYanException("冒烟了!");
System.out.println("电脑运行");
}
public void reset()
{
System.out.println("电脑重启!");
}
}
//-------------------------------------
class Teacher
{
private String name;
private Computer cmpt;
Teacher(String name)
{
this.name = name;
cmpt = new Computer();
}
public void prelect() throws NoPlanException
{
try
{
cmpt.run();
}
catch (LanPingException e)
{
cmpt.reset();
}
catch (MaoYanException e)
{
test();
throw new NoPlanException("课时无法继续"+e.getMessage());
}
System.out.println("讲课!");
}
public void test()
{
System.out.println("练习!");
}
}
//-------------------------------------------
class ExceptionTest
{
public static void main(String[] args)
{
Teacher t = new Teacher("毕老师");
try
{
t.prelect();
}
catch (NoPlanException e)
{
System.out.println(e.toString());
System.out.println("换老师,或者放假!");
}
}
} |