JAVA基础——异常类

来源:互联网 发布:php一键安装包 编辑:程序博客网 时间:2024/05/29 14:14
针对本周JAVA学习的异常类进行更深的练习和学习

//自定义两个本项目的异常
class LanPingException extends Exception
{
 LanPingException() {
  super();
 }
 LanPingException(String message) {
  super(message);
 }
}
class MaoYanException extends Exception
{
 MaoYanException() {
  super();
 }
 MaoYanException(String message) {
  super(message);
 }
}
//讲课中会发生的课时进度无法继续异常
class NoPlanException extends Exception
{
 NoPlanException() {
  super();
 }
 NoPlanException(String message) {
  super(message);
 }
}
class Computer
{
 private int state = 1;
 Computer(int state) {
  this.state = state;
 }
 public void run()throws LanPingException,MaoYanException {
  System.out.println("电脑运行");
  if ( state==2 )
   throw new LanPingException("电脑蓝屏了!");
  if ( state==3 )
   throw new MaoYanException("电脑冒烟了!");
 }
 public void reset() {
  state = 1;
  System.out.println("电脑重启");
 }
}
class Teacher
{
 private String name;
 private Computer comp;
 Teacher(String name, int state) {
  this.name = name;
  comp = new Computer(state);
 }
 public void prelect()throws NoPlanException {
  try
  {
   comp.run();
   System.out.println(name+"讲课");
  }
  catch (LanPingException e)
  {
   System.out.println(e.toString());
   //重启电脑
   comp.reset();
   prelect();
  }
  catch (MaoYanException e)//MaoYanException  e = new MaoYanException("电脑冒烟了!");
  {
   System.out.println(e.toString());
   test();
   throw new NoPlanException("课时进度停止:"+e.getMessage());
  }
 }
 public void test() {
  System.out.println("大家练习吧!");
 }
}
class Test01
{
 public static void main(String[] args)
 {
  Teacher t = new Teacher("张老师",3);
  try
  {
   t.prelect();
  }
  catch (NoPlanException e)
  {
   System.out.println(e.toString());
   try
   {
    new Teacher("李老师",1).prelect();
   }
   catch (NoPlanException ex)
   {
    System.out.println(ex.toString());
    System.out.println("大家放假");
   }
  }
 }
}

原创粉丝点击