一个简单可以体现面向对象思想及Java异常处理的代码演示
主要参与对象:使用者,手机
可能异常:
手机 - 死机,损坏(只列举两个)
使用者 - 不知所措
处理:
- 重启手机(手机)
- 重配手机(公司)
class DeathException extends Exception //手机异常1
{
DeathException(String msg)
{
super(msg);//调用父类方法
}
}
class BreakException extends Exception // 手机异常2
{
BreakException(String msg)
{
super(msg);//调用父类方法
}
}
class CanNotUseException extends Exception //手机使用者异常
{
CanNotUseException(String msg)
{
super(msg);
}
}
class Phone
{
private int state = 1;//表示手机运行状态,1表示正常,0表示死机,2表示机体损坏
void setState(int state)
{
this.state = state;
}
//手机运行
void run() throws DeathException,BreakException
{
if (state == 0)
throw new DeathException("宕机无反应");
else if (state == 2)
throw new BreakException("机体损坏关机");
else
System.out.println("手机正常运行");
}
//手机自己可以有的功能
void reset()
{
setState(1);
System.out.println("手机重启");
}
}
class User
{
private String id;//用户标识
private Phone p;
User(String id)
{
this.id = id;
p = new Phone();//用户拥有手机
}
Phone getP()
{
return p;
}
void usePhone() throws CanNotUseException
{
try
{
p.run();//用手机就可能发生异常,用try
System.out.println("id: "+id+" user phone do some job……");
}
catch (DeathException ex)
{
System.out.println(ex.toString());//输出异常信息
p.reset();//处理死机这种情况,重启
usePhone();//重新使用手机
}
catch (BreakException ex)
{
System.out.println(ex.toString());//同样输出异常信息
sendEmail();
throw new CanNotUseException("突然手机不能使用……原因:"+ex.toString());
//使用者给出的异常
}
}
void sendEmail()
{
System.out.println("我是……,手机坏了,暂时……");//手机无法工作的影响
//自我修复的一些功能
}
}
class DemoException
{
public static void main(String[] args)
{
//假如现在公司给的工作手机
User u = new User("Jim");
//演示程序,假设state为0
u.getP().setState(2);
try
{
u.usePhone();
}
catch (CanNotUseException ex)
{
System.out.println(ex.toString());
//公司处理办法
System.out.println("公司处理办法:换个新手机");
}
}
}