结构推理 根据所给创建自定义异常类的使用格式,编写一个自定义异常的小程序。
【正确答案】class Excp1 extends Exception { } class Excp2 extends Excp1 { } public class ExceptionExam7 { public static void main(String [] args) throws Exception { try { throw new Excp2(); } catch(Excp2 e) { System.out.println("catch1"); throw new Excp1(); } catch(Excp1 e) { System.out.println("catch2"); throw new Exception(); } catch(Exception e) { System.out.println("catch3"); } finally { System.out.println("finally"); } } } 说明: 自定义异常类,关键是选择继承的超类——必须是Exception或者其子类。用异常代表错误,而不要再使用方法返回值。
【答案解析】