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

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

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

package 测试;

public class 异常测试 {
	public static void main(String args[]) {
		System.out.println("-------异常测试-------");
		int []a = null;
		try {
			String str1=args[1];
			String str2=args[0];
			a[0]=Integer.parseInt(str1);
			a[1]=Integer.parseInt(str2);
			int temp=a[0]/a[1];
			System.out.println("两个数字相除结果:"+temp);
			System.out.println("--------------");
		}catch(ArrayIndexOutOfBoundsException e) {
			System.out.println("数组越界异常:"+e);
		}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{
	String 物品;
	public DangerException (){
		}
	boolean toShow() {
		return true;
	}
}

class Machine {
	 void checkBag(Goods goods) throws DangerException{
         if (goods.isDanger){
             throw new DangerException();
         }
     }
     public static void main(String[] args){
         Machine n = new Machine();
         String a[] = {"clothes","trousers","Computer","book","knife"};
         Goods goods[] = new Goods[5];
         for (int i = 0; i < goods.length; i++) {
             goods[i] = new Goods();
             goods[i].setLuggageName(a[i]);
             if((a[i]).equals("knife")) {
             goods[i].setisDanger(false);
             }
             else{
                 goods[i].setisDanger(true);
             }
             System.out.printf("%-12s", goods[i].getLuggageName());
             try{
                 n.checkBag(goods[i]);
             } catch (DangerException e){
                 System.out.print(e.toShow());
             }
             finally {
                 System.out.println("检查完毕");
             }
         }
     }
 }

class Goods {
	String Bag;
    boolean isDanger;
    void setLuggageName(String Bag){
        this.Bag = Bag;
    }
    String getLuggageName(){
        return Bag;
    }
    void setisDanger(boolean b){
        isDanger = b;
    }
    boolean getIsDanger(){
        return isDanger;
    }
}


作业写的非常的糊涂,感觉什么都不会

原文地址:https://www.cnblogs.com/he932206959/p/11698781.html