《JAVA异常处理》ArrayIndexOutOfBoundsException异常与OutOfMemoryError错误
2016-05-19 21:28
465 查看
1、【ArrayIndexOutOfBoundsException异常】编写一个程序,创建一个由100个随机选取的整数构成的数组;提示用户输入数组下标,然后显示元素的值,如果指定的下标越界,显示消息out of bounds。
2、【OutOfMemoryError错误】编写一个程序,它能导致JVM抛出一个OutOfMemoryError,然后捕获并处理这个错误。
![](http://img.blog.csdn.net/20160519211137688)
这些实验可以灵活变通,因为有挺多种方式写的,重要在于捕获与处理的过程,生成随机付给数组的代码也可以是:Array[i] = (int)(System.currentTimeMillis()),即利用产生系统的时间数并转化为整形,只是他们的范围太近了不好区分。初学者的看法,期待指正。
2、【OutOfMemoryError错误】编写一个程序,它能导致JVM抛出一个OutOfMemoryError,然后捕获并处理这个错误。
//1 package shiyan6; import java.util.Scanner; public class demo2 { public static void main(String[] args){ Scanner input = new Scanner(System.in); boolean inputIndex= true; int[]shuzu=new int[100]; //随机生成数字存入数组 for (int i=0;i<100;i++){ shuzu[i] = new java.util.Random().nextInt(100); } do{ try { System.out.println("Please in put the index of the shuzu[0-100]:"); int index = input.nextInt(); System.out.println(shuzu[index]); inputIndex= false;//输出之后退出 } catch (ArrayIndexOutOfBoundsException ex) { System.out.println("out of bounds!"); System.out.println("Please input again,index must be inputed from (0-100)"); } } while (inputIndex); } }
//2 方法一 不断输入数组的长度大小(在int范围之内),直到数组长度太大爆了 package shiyan6; import java.util.Scanner; public class demo3 { public static void main(String[] args) { boolean Stop =true; do{ try { System.out.println("Input an integer in of the range of (-2147483647~2147483647)"); Scanner input = new Scanner(System.in); int len = input.nextInt(); int largArray[] = new int[len]; Stop = false; } catch (OutOfMemoryError e) { System.out.println("OutOfMemoryError !"); } }while(Stop); } }
//2 方法二 直接产生一个最大的int 类型的整数直到数组长度爆了 package shiyan6; import java.util.Scanner; public class demo3 { public static void main(String[] args) { try { int len = Integer.MAX_VALUE; int largArray[] = new int[len]; System.out.println(len); } catch (OutOfMemoryError e) { e.printStackTrace(); System.out.println("Please input the munber of the array you want(lpease input small):"); Scanner input = new Scanner(System.in); int len2 = input.nextInt(); System.out.println("The maxindex of the array you input is:"+len2); } } }
这些实验可以灵活变通,因为有挺多种方式写的,重要在于捕获与处理的过程,生成随机付给数组的代码也可以是:Array[i] = (int)(System.currentTimeMillis()),即利用产生系统的时间数并转化为整形,只是他们的范围太近了不好区分。初学者的看法,期待指正。
相关文章推荐
- kettle运行时报错 could not create java virtual machine
- 攻破JAVA NIO技术壁垒
- 攻破JAVA NIO技术壁垒
- java基础学习总结——面向对象
- JavaWeb开发-Eclipse Java注释模版设置方法
- 【Java基础】面向对象特性
- 《栈 队列》——栈与队列(Java)
- 深入理解Java虚拟机总结-思维导图
- 认识Java Core和Heap Dump
- [Java]HashMap源码分析
- POJ 1001 Exponentiation(大数幂Java实现)
- java抽象类,接口
- Struts2_ActionSupport和通配符映射和动态方法调用
- JAVA设计模式(19):行为型-观察者模式(Observer)
- java模拟接口回调
- java读写ini文件、FileOutputStream
- JAVA 大整数类
- Java 集合小结
- java之stream(jdk8)
- 个人对Spring @Scope("prototype")的一些理解