Java实验6《异常处理》

一、实验目的

  1. 编写try-catch块处理异常

二、实验内容

  1. 【NumberFormatException异常】编写一个程序,提示用户输入两个整数,然后显示它们的和。用户输入错误时提示用户重新输入。

1.1 程序代码:

import java.util.*;
public class program1{
    public static void main(String[] args){
    Scanner input = new Scanner(System.in);
    boolean continueInput = true;
  
    do{
        try{
           //提示输入两个整数
           System.out.println("请输入两个整数:");
           String x = input.next();
           String y = input.next();

           //输出求和结果
           System.out.println(x + " + " + y + " = " + (Integer.valueOf(x)+Integer.valueOf(y)) );
           continueInput = false;
        }//try结束
        catch(NumberFormatException ex){
          System.out.print("输入错误(NumberFormatException),");
          input.nextLine();
        }//catch结束
    }while(continueInput);

    }//main方法结束
}//program1结束

1.2 运行结果:
Java实验6《异常处理》_第1张图片
  运行结果正确,符合题目要求,提示用户输入两个整数,输入类型错误时重新输入直到正确。

1.3 心得体会:
  书本例题稍作修改,熟悉异常处理的类型及语法即可。错误类型NumberFormatException是类型转换错误,这个要尤其注意。


  1. (P419, 12.3)【ArrayIndexOutOfBoundsException异常】编写一个程序,创建一个由100个随机选取的整数构成的数组;提示用户输入数组下标,然后显示元素的值,如果指定的下标越界,显示消息out of bounds。

2.1 程序代码:

import java.util.*;
public class program2{
    public static void main(String[] args){
    Scanner input = new Scanner(System.in);
    int[] array = new int[100];
    //用[0,100)之间的数初始化数组
    for(int i=0; i<100; i++)
          array[i] = (int)(Math.random() * 100);
    
    try{
         System.out.println("请输入数组的下标:");
         int index = input.nextInt();
         System.out.println("array[" + index +"] : " + array[index]);
    }
    catch(IndexOutOfBoundsException ex){
        System.out.println("out of bounds");
    }

    }//main方法结束
}//program结束

2.2 运行结果:
Java实验6《异常处理》_第2张图片 Java实验6《异常处理》_第3张图片
  运行正确,符合题目要求,输入数组下标,在范围内则输出该下标下数组的值,超出范围则输出:out of bounds

2.3 心得体会:
  创建一个用随机数初始化的数组,用户输入下标,范围内则输出数据,范围外做异常处理,try和catch以及错误类型(indexOutOfBoundsException)的应用。


  1. (P420, 12.10)【OutOfMemoryError错误】编写一个程序,它能导致JVM抛出一个OutOfMemoryError,然后捕获并处理这个错误。

3.1 程序代码:

//编写一个能抛出OutOfMemoryError的程序
import java.util.*;
public class program3{
    public static void main(String[] args){
    long startTime = System.currentTimeMillis();
    try{
      ArrayList<Object> list = new ArrayList<>();
        while(true)
            list.add(new Object());
    }
    catch(OutOfMemoryError ex){
         System.out.println("Out of memory");
    }

    long endTime = System.currentTimeMillis();
    System.out.println("(测试用时:" + (endTime - startTime) + "ms)");

    }//main结束
}//program3结束

3.2 运行结果:
Alt
  运行结果符合题目要求,编写一个能导致JVM抛出OutOfMemoryError的程序,个人编写程序内容为创建数组,不断添加实例元素,直至JVM崩溃(附带程序JVM崩溃时长)。

3.3 心得体会:
  个人编写了一个“创建数组,不断添加实例元素,直至JVM崩溃”的程序(附带崩溃时长)用于使JVM抛出一个OutOfMemoryError的异常。使用while(true)不断给数组添加实例元素,只要时间充足,JVM迟早崩溃。


你可能感兴趣的:(Java)