- 一、实验目的及要求
- 1.实验目的
- 2.实验要求
- 二、实验环境
- 三、实验内容(实验方案、实验步骤、设计思路等)
- 四、实验结果与分析
- 五、附源代码
- 掌握异常类中的try-catch语句和自定义异常类;
- 对程序运行中出现的各种异常进行处理;
- 熟悉并学会自定义异常对象的方法。
- 弄清楚try-catch语句和自定义异常类在错误产生时的程序控制流程;
- 能够对程序运行时可能出现的问题进行处理,并给出产生异常情况下的具体 *** 作;
- 掌握自定义异常类的方法
- 硬件要求:一台电脑(带Windows 10 *** 作系统)
- 软件要求: JDK-14.0.2,Intellij IDEA 2020.1.2
- 实验方案:编写一个Java类,其中的异常类继承Exception,Ship类提供抛出异常的方法,最后由主类实现。
- 实验步骤:先编写异常类,并为其提供方法。然后编写Ship类,主类中创建Ship对象,使用try-catch语句捕获异常。
- 设计思路:在主类中创建对象后,使用try-catch语句,主动令抛出异常的方法抛出异常,以便于被catch语句捕获,根据输出语句判断程序运行到了哪个位置。
package com; class Ship { private int cargo;//船上货物量 Ship(int cargo) {//需要初始货物量 this.cargo = cargo; } void addCargo() {//加货 cargo = cargo + 100; } void downCargo(int num) throws EmptyException {//卸货,货不足则抛出异常 if(num >cargo){ String message = "在装货前,这艘船是空的。"; throw new EmptyException(this, message); } else { cargo = cargo - num; } } } class EmptyException extends Exception{ EmptyException(Ship ship,String s) { super(s);//传递异常信息 ship.addCargo(); System.out.println("需要一些货"); } } public class Main { public static void main(String[] args) { int initial = 100; Ship ship=new Ship(initial); try { System.out.println("需要装货。");//测试正常情况 ship.downCargo(80); System.out.println("现在要使用80吨货。"); ship.downCargo(20); System.out.println("需要另外20吨货。"); ship.downCargo(30);//此次抛出异常 System.out.println("30吨货。"); } catch (EmptyException e) { String message = e.getMessage();//获取异常信息 System.out.println("一个异常出现");//用于标记位置 System.out.println(message); } } }
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)