第1个回答 2012-03-30
@SuppressWarnings("serial")
public class ChildError extends Exception {
public final Child who;
public ChildError(Child child, String msg) {
super(msg);
this.who = child;
}
}
/**
* 不及格。
*/
@SuppressWarnings("serial")
public class FlunkError extends ChildError {
public FlunkError(Child child, String msg) {
super(child, msg);
}
}
/**
* 偷东西。
*/
@SuppressWarnings("serial")
public class StealError extends ChildError {
public StealError(Child child, String msg) {
super(child, msg);
}
}
public class Parent {
public void educate(ChildError error){
if(error instanceof FlunkError){
this.talk((FlunkError) error);
}else if(error instanceof StealError){
this.beat((StealError) error);
}
}
/**
* 谈心。
*/
public void talk(FlunkError error){
System.out.println("父母说:“没事的”。");
}
/**
* 打。
*/
public void beat(StealError error){
System.out.println("父母怒打。");
}
}
public class Child {
private Parent parent;
public Child(Parent parent) {
super();
this.parent = parent;
}
public Parent getParent() {
return this.parent;
}
/**
* 考试。
*/
public void takeExamination() throws FlunkError{
System.out.println("孩子去考试。");
throw new FlunkError(this, "孩子考试不及格!");
}
/**
* 购物。
*/
public void shopping() throws StealError{
System.out.println("孩子去购物。");
throw new StealError(this, "孩子偷东西!");
}
}
public class Test {
public static void main(String[] args) {
Child c = new Child( new Parent() );
try {
c.takeExamination();
} catch (ChildError e) {
c.getParent().educate(e);
}
try {
c.shopping();
} catch (ChildError e) {
c.getParent().educate(e);
}
}
}