package com.day0323.ExceptionPractise;
public class WorkDemo {
public static void main(String[] args) {
Car car = new Car();
Worker w = new Worker(car);
try {
w.gotoWork();
System.out.println("上班没有迟到");
} catch (LateException e) {
e.printStackTrace();
System.out.println("上班迟到");
}
}
}
class Car{
private int x = 2;
public void run(){
if (x == 2) {
throw new CarWrongException("车抛锚了");
}
System.out.println("开车上班");
}
}
class Worker{
Car car = null;
Worker(Car car){
this.car = car;
}
public void gotoWork(){
try {
car.run();
System.out.println("正常上班");
} catch (CarWrongException e) {
e.printStackTrace();
this.walk();
throw new LateException("迟到原因:"+e.getMessage());
}
}
private void walk() {
System.out.println("走路去上班");
}
}
class CarWrongException extends RuntimeException {
private static final long serialVersionUID = 1L;
public CarWrongException() {
super();
}
public CarWrongException(String arg0, Throwable arg1) {
super(arg0, arg1);
}
public CarWrongException(String arg0) {
super(arg0);
}
}
class LateException extends Exception {
private static final long serialVersionUID = 1L;
public LateException() {
super();
}
public LateException(String arg0, Throwable arg1) {
super(arg0, arg1);
}
public LateException(String arg0) {
super(arg0);
}
} |
|