第九章章节练习
第一题
1 package com.kgc.zzlx.zhangjie9.zhangjie901; 2 3 /** 4 * 测试类 5 */ 6 public class Test { 7 public static void main(String[] args){ 8 NullError a=new NullError(); 9 try { 10 a.setSex(null); 11 }catch (NullPointerException e){ 12 e.printStackTrace(); 13 }finally { 14 System.err.println("空指针异常......"); 15 } 16 17 } 18 }
1 package com.kgc.zzlx.zhangjie9.zhangjie901; 2 3 /** 4 * 空指针异常 5 */ 6 public class NullError { 7 private String sex; 8 9 public String getSex() { 10 return sex; 11 } 12 13 public void setSex(String sex) { 14 if (sex.equals("男")){ 15 this.sex = sex; 16 }else{ 17 18 } 19 20 } 21 22 public NullError() { 23 } 24 25 public NullError(String sex) { 26 this.sex = sex; 27 } 28 }
运行结果

第二题
1 package com.kgc.zzlx.zhangjie9.zhangjie902; 2 3 import java.util.Scanner; 4 5 /** 6 * 测试类 7 */ 8 public class Test { 9 public static void main(String[] args){ 10 Scanner sc=new Scanner(System.in); 11 Chengji cj=new Chengji(); 12 System.out.print("请输入成绩:"); 13 try{ 14 cj.setChengji(sc.nextInt()); 15 }catch (ChengjiError e){ 16 e.printStackTrace(); 17 } 18 19 } 20 }
1 package com.kgc.zzlx.zhangjie9.zhangjie902; 2 3 /** 4 * 自定义异常 5 */ 6 public class ChengjiError extends Exception { 7 public ChengjiError(String a){ 8 super(a); 9 } 10 }
1 package com.kgc.zzlx.zhangjie9.zhangjie902; 2 3 /** 4 * 成绩 5 */ 6 public class Chengji { 7 private int chengji; 8 9 public int getChengji() { 10 return chengji; 11 } 12 13 public void setChengji(int chengji) throws ChengjiError{ 14 if (chengji>=0&&chengji<=100){ 15 this.chengji = chengji; 16 }else{ 17 throw new ChengjiError("请输入正确的成绩信息!"); 18 } 19 20 } 21 22 public Chengji() { 23 } 24 25 public Chengji(int chengji) { 26 this.chengji = chengji; 27 } 28 }
运行结果


浙公网安备 33010602011771号