/*
* 需求:教师用电脑上课
*
* 上课中出现的问题
* 比如:电脑蓝屏
* 电脑冒烟
*
* 对问题进行描述,封装成对象
*
* 可是当冒烟发生后,出现讲课进度无法继续
* 出现了讲师的问题,课时计划无法完成
*
* */
class LanPingException extends Exception {
LanPingException(String message) {
super(message);
}
}
class MaoYanException extends Exception {
MaoYanException(String message) {
super(message);
}
}
class NoPlanException extends Exception{
public NoPlanException(String message) {
// TODO Auto-generated constructor stub
super(message);
}
}
class Teacher {
private String name;
private Computer computer;
Teacher(String name) {
this.name = name;
computer = new Computer();
}
public void perlect() throws NoPlanException{
try {
computer.run();
} catch (LanPingException e) {
// TODO: handle exception
computer.reboot();
}
catch (MaoYanException e) {
// TODO: handle exception
test();
throw new NoPlanException("无法讲课"+e.getMessage());
}
System.out.println("讲课");
}
public void test(){
System.out.println("练习");
}
}
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 reboot() {
state = 1;
System.out.println("电脑重启");
}
}
public class ExceptionTest {
public static void main(String args[]) {
Teacher teacher = new Teacher("老师");
try{
teacher.perlect();
}
catch (NoPlanException e) {
// TODO: handle exception
System.out.println(e.toString());
System.out.println("换老师或换电脑");
}
}
}
再一个
/*
* 有一个圆形和长方形
* 都可以获取面积,对于面积如果出现非法的数值,视为是获取面积出现问题
* 问题通过异常来表示
*
* 程序设计
*
*
* */
class IllegalNumberException extends RuntimeException{
public IllegalNumberException(String mString) {
// TODO Auto-generated constructor stub
super(mString);
}
}
abstract interface Area{
int area() throws IllegalNumberException;
}
class Circle implements Area{
private int radius;
public static final int π=3;
public Circle(int radius) {
// TODO Auto-generated constructor stub
if(0>=radius)
throw new IllegalNumberException("出现错误数据");
this.radius=radius;
}
public int area() throws IllegalNumberException{
int area=π*this.radius*this.radius;
return area;
}
}
class Rectangle implements Area{
private int height,weight;
public Rectangle(int height,int weight) {
// TODO Auto-generated constructor stub
if(0>=height||0>=weight)
throw new IllegalNumberException("出现错误数据");
this.height=height;
this.weight=weight;
}
public int area(){
int area=this.height*this.weight;
return area;
}
}
public class ExceptionTest2 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Rectangle rectangle=new Rectangle(4, 3);
System.out.println("长方形面积:"+rectangle.area());
Circle circle=new Circle(3);
System.out.println("圆形面积:"+circle.area());
}
}
-------------------------By 仔鸡