第六周课程总结&实验报告

实验报告六
编写一个类,在其main()方法中创建一个一维数组,在try字句中访问数组元素,使其产生ArrayIndexOutOfBoundsException异常。在catch子句里捕获此异常对象,并且打印“数组越界”信息,加一个finally子句,打印一条信息以证明这里确实得到了执行。
自定义异常类的使用
实验代码:

package 异常类;

public class 异常 {
    public static void main(String[] args) {
        System.out.println("程序运行");
        int ch[]= {1,2,3,3};
        try {
                System.out.print(ch[8]);
            }catch(ArrayIndexOutOfBoundsException a){
                System.out.println("数组越界:"+a);![](https://img2018.cnblogs.com/blog/1581356/201910/1581356-20191019085203764-1961604084.png)


            }finally {            
                System.out.println("无论程序是否正常都执行");
            }
}
}

技术方案:
编写一个Exgeption的子类DangerException,该子类可以创建异常对象,该异常对象调用toShow()方法输出“危险物品”。编写一个Machine类,该类的方法checkBag(Goods goods)当发现参数goods是危险品时(goods的isDanger属性是true)将抛出DangerException异常。
程序在主类的main()方法中的try-catch语句的try部分让Machine类的实例调用checkBag(Goods goods)的方法,如果发现危险品就在try-catch语句的catch部分处理危险品。

package 异常类;

public class DangerException extends Exception{
     
     public void toShow() {
        System.err.println("危险物品!!!");
     }
}
public class Goods {
     private String name;
        boolean isDanger = true;

        public Goods(String name) {
            this.name = name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public String getName() {
            return name;
        }

}public class Machine {
     public void checkBag(Goods goods) throws DangerException {

            DangerException danger = new DangerException();
            throw danger;
        }
}import java.lang.constant.Constable;
import java.util.ArrayList;
import java.util.Scanner;
public class text {
     public static void main(String[] args) {
            System.out.println("请输入要添加的危险品:");
            Scanner a = new Scanner(System.in);
            String d = a.next();
            
            ArrayList<String> list = new ArrayList<String>();
            
            String a1=d;
            list.add(a1);
            list.add("刀");
            list.add("黄诗荣");
            list.add("王滇");
            list.add("彭定康");
            list.add("女生");
            list.add("枪");
            System.out.println("请输入要检查的物品:");
            Scanner n = new Scanner(System.in);
            String x = n.next();
            Goods goods = new Goods(x);
            Machine ma = new Machine();
            try {
                ma.checkBag(goods);
            } catch (DangerException ae) {
                if (list.contains(x)) {
                    ae.toShow();
                    System.err.println( "不能通过: "+goods.getName() );
                } else {
                    System.out.println( "检查通过: "+goods.getName() );
                }
            }
        }
}

总结
1.了解了try{}catch{}finally{}的基本用法
2.了解了Thread类runnable接口的运用方法
3.学习了throw与throws
4.学习了对于编写识别危险品操作的简单代码

posted @ 2019-10-19 08:53  可惜她是水瓶座  阅读(78)  评论(0编辑  收藏  举报