public class ScaryException extends Exception {
public ScaryException() {
super();
}
public ScaryException(String message) {
super(message);
}
public ScaryException(String message, Throwable cause ) {
super(message, cause);
}
public ScaryException(Throwable cause) {
super(cause);
}
}
public class TestExceptions {
public static void doRisky(String test) throws ScaryException {
System.out.println("start risky......");
//用Object 引用 String 类,是因为 Object 本身是String 类的父类
//拥有 String 类重写的方法。
if ("yes".equals(test)) {
throw new ScaryException();
}
System.out.println("end risky......");
}
public static void main(String[] args) {
String test = "no";
try {
System.out.println("start try......");
doRisky(test);
System.out.println("end try......");
} catch (ScaryException se) {
System.out.println("scary exception");
} finally {
System.out.println("finally......");
}
System.out.println("end of main.");
}
}
class BaseballException extends Exception {}
class Foul extends BaseballException {}
class Strike extends BaseballException {}
abstract class Inning {
public Inning() throws BaseballException {}
public void event() throws BaseballException {
}
public abstract void atBat() throws Strike, Foul;
public void walk() {}
}
class StormException extends Exception {}
class RainedOut extends StormException {}
class PopFoul extends Foul {}
interface Storm {
public void event();
public void rainHard() throws RainedOut;
}
public class StormyInning extends Inning implements Storm {
// 构造函数可以添加新的异常,但是必须处理父类的异常
public StormyInning() throws RainedOut, BaseballException {
}
public StormyInning(String s) throws Foul, BaseballException {
}
/* 父类的方法没有异常的不能添加异常
public void walk() throws PopFoul {
}*/
// 接口不能为父类中存在的方法添加异常
public void event() {
}
@Override
public void rainHard() throws RainedOut {
// TODO Auto-generated method stub
}
// 可以窄化抛出的异常 PopFoul 可以用来替换 Strike, Foul
@Override
public void atBat() throws Strike, Foul {
// TODO Auto-generated method stub
}
}