Java-解决开车上班案例

//车坏的异常
class  CarWrongException extends RuntimeException{
	private static final long serialVersionUID = 1L;

public CarWrongException(String message, Throwable cause) {
		super(message, cause);
	}

	public CarWrongException(String message) {
		super(message);
	}
}
//上班 迟到
	class  LateException extends RuntimeException{
		private static final long serialVersionUID = 1L;

	public LateException(String message, Throwable cause) {
			super(message, cause);
		}

		public LateException(String message) {
			super(message);
		}
}
//车
class Car {

	public  void run(){
		int i = 1;
		if (i == 1) {
		throw new CarWrongException("车胎boom" );
		} 
			System.out.println("车子正常走");		
		
	}
}

class Person {
	private Car car =null;
	Person (Car car ){
	this.car = car;
	}

	public void goWork() {
		try {
			car.run();//正常上班
			System.out.println("正常上班");
		} catch (CarWrongException e) {
			e.printStackTrace();
			//车抛锚了,异常情况
			this.walk();
			throw new LateException("迟到的原因" +e.getMessage(),e);
		}
	}

	private void walk() {
		System.out.println("走路上班必迟到");
		
	}
}
	



public class WhyDemo {
	public static void main(String[] args)  {
		Car c = new Car();
		Person p = new Person(c);
		try {
			p.goWork();
		} catch (LateException e) {
e.printStackTrace()	;	}
		 
		}
	}

 

版权声明:
作者:yfeer
链接:https://www.yfeer.com/704.html
来源:个人编程学习网
文章版权归作者所有,未经允许请勿转载。

THE END
分享
二维码
< <上一篇
下一篇>>