实验六 Java异常
实验代码:
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(异常类 异常对象)
{
//编写异常的处理语句
}
finally
{
//一定会运行的代码
}
不管出现什么异常都可以用Exception来处理异常对象。
throws声明的方法此方法不处理异常
throw是抛出一个异常,抛出时直接抛出异常类的实例化对象
自定义异常类需要继承Exceptio这个父类
原文:https://www.cnblogs.com/lsy2380821-/p/11700293.html