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

实验六 Java异常

实验目的
理解异常的基本概念;
掌握异常处理方法及熟悉常见异常的捕获方法。
实验要求
练习捕获异常、声明异常、抛出异常的方法、熟悉try和catch子句的使用。
掌握自定义异常类的方法。

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

public class text {
    public static void main(String[] args) {
        System.out.println("程序开始运行");
        
        int a[] = {0,1,2};
        
        try{
            System.out.println(a[4]);
        }catch(ArrayIndexOutOfBoundsException e){
            System.out.println("数组越界异常");
        }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 text2333;

import java.util.ArrayList;
import java.util.Scanner;

class DangerException extends Exception {
    String massage;

    public DangerException() {
        this.massage = "危险物品!";
    }

    public void toShow() {
        System.err.println("危险物品");
    }

}

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;
    }

}

class Machine {

    public void checkBag(Goods goods) throws DangerException {

        DangerException danger = new DangerException();
        throw danger;

    }

}

public class test {
    public static void main(String[] args) {
        ArrayList<String> list = new ArrayList<String>();
        list.add("刀具");
        list.add("汽油");
        list.add("枪支");
        list.add("弹药");
        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() + ":检查通过");
            }
        }
    }
}


学习总结:
学习了熟悉try和catch子句的使用 掌握自定义异常类的方法

posted @ 2019-10-18 20:19  幼稚动感男  阅读(187)  评论(1编辑  收藏  举报