- 方法内, throw是生成异常,结束当前方法运行,此时要么捕获(自己抛的自己捕获,没有意义),要么上抛,即方法上throws声明,让调用者处理
- throws是处理异常(抛给别人处理),方法内throw了异常没有捕获处理,必须通过throws声明,让调用者处理
- 方法上throws 用于声明方法可能会抛出哪些异常
- RuntimeException
- 方法内throw了异常,方法上可以不用生命,编译一样通过,为啥? 因为希望程序终止而不是让让调用者处理
- 方法上声明了该异常,调用者可以不用处理,一样编译过。原因同上。
class LanPingException extends Exception
{
LanPingException(String message)
{
super(message);
}
}
class MaoYanException extends Exception
{
MaoYanException(String message)
{
super(message);
}
}
class NoPlanException extends Exception
{
NoPlanException(String msg)
{
super(msg);
}
}
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()
{
state = 1;
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("换老师或者放假");
}
}
}