java课堂作业(十二)
题目:自定义一个学生类和相应异常类,属性有:姓名、年龄。如果用户在给学生年龄赋值时,如果年龄小于0 则抛出一个AgeLT0Exception,如果年龄大于150 抛出一个AgeGT150Exception
1 package com.zhuoyue.ch12; 2 3 public class AgeLT0Exception extends Exception{ 4 5 /** 6 * 7 */ 8 private static final long serialVersionUID = -3655506382017253195L; 9 10 public AgeLT0Exception(){ 11 super(); 12 } 13 14 public AgeLT0Exception(String message){ 15 super(message); 16 } 17 18 }
1 package com.zhuoyue.ch12; 2 3 public class AgeGT150Exception extends Exception { 4 5 /** 6 * 7 */ 8 private static final long serialVersionUID = -2518423261295977881L; 9 10 public AgeGT150Exception(){ 11 super(); 12 } 13 14 public AgeGT150Exception(String message){ 15 super(message); 16 } 17 18 }
1 package com.zhuoyue.ch12; 2 3 public class TestException { 4 5 public static void main(String[] args) { 6 //要么捕获异常,程序员处理。要么抛出异常,有上一级处理 7 try { 8 Student s1 = new Student("小明",-1); 9 } catch (AgeLT0Exception e) { 10 // TODO Auto-generated catch block 11 e.printStackTrace(); 12 } catch (AgeGT150Exception e) { 13 // TODO Auto-generated catch block 14 e.printStackTrace(); 15 } 16 17 try { 18 Student s2 = new Student("小红",156); 19 } catch (AgeLT0Exception e) { 20 // TODO Auto-generated catch block 21 e.printStackTrace(); 22 } catch (AgeGT150Exception e) { 23 // TODO Auto-generated catch block 24 e.printStackTrace(); 25 } 26 } 27 28 }