2019-2-19 异常练习

一、根据编号输出课程名称

代码块:

 1 package com.test;
 2 
 3 import java.util.Scanner;
 4 
 5 /**
 6  * 根据编号输出课程名称
 7  * @author Mr.kemi
 8  * 2019-2-19   2019过去了78天   我还在干什么!!!
 9  * 今日新单词 Course 课程、进程
10  */
11 public class Course {
12     public static void main(String[] args) {
13         Scanner input = new Scanner(System.in);
14         System.out.println("请输入课程代号(1~~3之间的数字):");
15         int i = input.nextInt();
16         //try 执行可能产生异常的代码
17         try {
18             if(i == 1) {
19                 System.out.println("C#课程");
20             }else if(i == 2) {
21                 System.out.println("C++课程");
22             }else if(i == 3) {
23                 System.out.println("Java课程");
24             }else {
25                 System.out.println("您输入的课程代码有误,请重新输入");
26             }
27             //catch 捕获异常
28         }catch(Exception e) {
29             //识别异常,报出来
30             e.printStackTrace();
31             //从java虚拟机退出
32             System.exit(1);
33             //finally 无论是否发生异常,代码总能运行
34         }finally {
35             System.out.println("欢迎提出建议");
36         }        
37     }
38 }

执行后:

输入正确时,弹出课程

输入错误时,提醒错误

本次作业知识点:

1、运用到异常3个关键字› finally»无论怎么样都会执行、try» 可能发生异常的代码 、catch »捕获异常。

2、判断可能发生异常的代码放入try中  在catch中捕获异常,并提示然后退出程序  最后在执行一定要执行的语句用finally。

结论:

语法要记牢,用法要记清,代码要多练习。

二、使用throw抛出年龄异常

代码块↓↓↓

自定义异常:

1 package com.test;
2 
3 public class AgeErrorException extends Exception {
4     public AgeErrorException (String mess) {
5         super(mess);
6     }
7 }

创建类:

 1 package com.test;
 2 /**
 3  * 使用throw 抛出年龄异常
 4  * @author Mr.kemi
 5  * 人类
 6  */
 7 public class Age {
 8     private int age;
 9 
10     public int getAge() {
11         return age;
12     }
13     public void setAge(int age)throws AgeErrorException {
14         if(age>=1&&age<=100) {
15             this.age = age;
16         }else {
17             //抛出异常
18             throw new AgeErrorException("年龄必须在1-100之间!");
19         }
20         
21     }
22     
23 }

测试类:

package com.test;
/**
 * 测试类
 * @author Administrator
 *
 */
public class TestAge {
    public static void main(String[] args) {
        Age a = new Age();
        try {
            a.setAge(111);
        }catch(Exception e){
            e.printStackTrace();
        }
    }
}

执行后:

本次作业知识点:

1、运用到异常2个关键字› try» 可能发生异常的代码 、catch »捕获异常。

2、学会如何自定义异常,抛出异常throw 声明异常 throws

3、最后构建方法对象,执行

结论:

语法要记牢,用法要记清,代码要多练习。

原文地址:https://www.cnblogs.com/kemii/p/10408067.html