201771010123汪慧和《面向对象程序设计JAVA》第九周实验总结

一、理论部分

1、异常

(1)异常处理的任务就是将控制权从错误产生的地方转移给能够处理这种情况的错误处理器。

(2)程序中可能出现的错误和问题:a.用户输入错误。b.设备错误。c.物理限制。d.代码错误。

(3)异常分为致命异常和非致命异常。

(4)异常对象都是派生于Throwable类的一个实例。如果java中内置的异常类不能满足需求,用户可以创建自己的异常类。

(5)Java异常层次结构简化示意图如下:

 2、所有的异常都是由Throwable类继承而来,在下一层分解为两个分支:Error和Exception。

(1)Error类层次结构描述了Java运行时系统的内部错误和资源耗尽错误。应用程序不应该抛出这种类型的对象。

(2)在设计Java程序时,需要关注Exception层次结构。这个层次结构又分解为两个分支:一个分支派生于RuntimeException;另一个分支包含其他异常。

3、派生于于RuntimeException的异常包含下面几种情况:

(1)错误的类型转换。

(2)数组访问越界。

(3)访问null指针。

4、不是派生于于RuntimeException的异常包含下面几种情况:

(1)试图在文件尾部后面读取数据。

(2)试图打开一个不存在的文件。

(3)试图根据给定的字符串查找Class对象,而这个字符串表示的类不存在。

5、Java将派生于Error或RuntimeException类的所有异常称为未检查异常。

二、实验内容

1、实验目的与要求

(1) 掌握java异常处理技术;

(2) 了解断言的用法;

(3) 了解日志的用途;

(4) 掌握程序基础调试技巧;

2、实验内容和步骤

实验1:用命令行与IDE两种环境下编辑调试运行源程序ExceptionDemo1、ExceptionDemo2,结合程序运行结果理解程序,掌握未检查异常和已检查异常的区别。

//异常示例1

public class ExceptionDemo1 {

public static void main(String args[]) {

int a = 0;

System.out.println(5 / a);

}

}

//异常示例2

import java.io.*;

public class ExceptionDemo2 {

public static void main(String args[]) 

     {

          FileInputStream fis=new FileInputStream("text.txt");//JVM自动生成异常对象

          int b;

          while((b=fis.read())!=-1)

          {

              System.out.print(b);

          }

          fis.close();

      }

}

检查异常后;

//异常示例1
public class ExceptionDemo1 {
    public static void main(String args[]) {
        int a=0;
        if(a==0) {
            System.out.println("除数为零!");
        }
        else {
            System.out.println(5 / a);

        }
    }
}

 

//异常示例2
import java.io.*;

public class ExceptionDemo2 {
    public static void main(String args[]) throws Exception 
   {
        FileInputStream fis=new FileInputStream("text.txt");//JVM自动生成异常对象
        int b;
        while((b=fis.read())!=-1)
        {
            System.out.print(b);
        }
        fis.close();
    }
}

实验2: 导入以下示例程序,测试程序并进行代码注释。

测试程序1:

l 在elipse IDE中编辑、编译、调试运行教材281页7-1,结合程序运行结果理解程序;

l 在程序中相关代码处添加新知识的注释;

l 掌握Throwable类的堆栈跟踪方法;

import java.util.*;

/**
 * A program that displays a trace feature of a recursive method call.
 * @version 1.01 2004-05-10
 * @author Cay Horstmann
 */
public class StackTraceTest
{
   /**
    * Computes the factorial of a number
    * @param n a non-negative integer
    * @return n! = 1 * 2 * . . . * n
    */
   public static int factorial(int n)
   {
      System.out.println("factorial(" + n + "):");
      Throwable t = new Throwable();
      StackTraceElement[] frames = t.getStackTrace();//调用Throwable类的getStackTrace方法,得到StackTraceElement对象的一个数组
      for (StackTraceElement f : frames)
         System.out.println(f);
      int r;
      if (n <= 1) r = 1;
      else r = n * factorial(n - 1);
      System.out.println("return " + r);
      return r;
   }

   public static void main(String[] args)
   {
      Scanner in = new Scanner(System.in);
      System.out.print("Enter n: ");
      int n = in.nextInt();
      factorial(n);
   }
}

 运行结果如下图所示:

测试程序2:

l Java语言的异常处理有积极处理方法和消极处理两种方式;

l 下列两个简答程序范例给出了两种异常处理的代码格式。在elipse IDE中编辑、调试运行源程序ExceptionalTest.java,将程序中的text文件更换为身份证号.txt,要求将文件内容读入内容,并在控制台显示;

l 掌握两种异常处理技术的特点。

//积极处理方式  

import java.io.*;

class ExceptionTest {

public static void main (string args[])

   {

       try{

       FileInputStream fis=new FileInputStream("text.txt");

       }

       catch(FileNotFoundExcption e

     {   ……  }

……

    }

}

//消极处理方式

import java.io.*;

class ExceptionTest {

public static void main (string args[]) throws  FileNotFoundExcption

     {

      FileInputStream fis=new FileInputStream("text.txt");

     }

}

package 异常;

//积极处理方式  
import java.io.*;
import java.io.BufferedReader;
import java.io.FileReader;

class ExceptionTest {
    public static void main (String args[])
 {
        File fis=new File("E:\身份证号.txt");
     try{
         

         FileReader fr = new FileReader(fis);
         BufferedReader br = new BufferedReader(fr);
         try {
             String s, s2 = new String();
             while ((s = br.readLine()) != null) {
                 s2 += s + "
 ";
             }
             br.close();
             System.out.println(s2);
         } catch (IOException e) {
             // TODO自动生成的catch块
             e.printStackTrace();
         }
     } catch (FileNotFoundException e) {
         // TODO自动生成的catch块
         e.printStackTrace();
     }

  }
}
package 异常;

//消极处理方式

import java.io.*;
class ExceptionTest1 {
    public static void main (String args[]) throws  IOException
       {
        File fis=new File("身份证号.txt");
        FileReader fr = new FileReader(fis);
        BufferedReader br = new BufferedReader(fr);
        String s, s2 = new String();

            while ((s = br.readLine()) != null) {
                s2 += s + "
 ";
            }
            br.close();
            System.out.println(s2);
       }
}
package 异常;

//消极处理方式

import java.io.*;
class ExceptionTest1 {
    public static void main (String args[]) throws  IOException
       {
        File fis=new File("身份证号.txt");
        FileReader fr = new FileReader(fis);
        BufferedReader br = new BufferedReader(fr);
        String s, s2 = new String();

            while ((s = br.readLine()) != null) {
                s2 += s + "
 ";
            }
            br.close();
            System.out.println(s2);
       }
}

实验结果如下图所示:

实验3: 编程练习

练习1

l 编制一个程序,将身份证号.txt 中的信息读入到内存中;

l 按姓名字典序输出人员信息;

l 查询最大年龄的人员信息;

l 查询最小年龄人员信息;

l 输入你的年龄,查询身份证号.txt中年龄与你最近人的姓名、身份证号、年龄、性别和出生地;

l 查询人员中是否有你的同乡;

l 在以上程序适当位置加入异常捕获代码。

注:以下实验课后完成

package IDcard;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Scanner;
import java.util.Collections;

public class ID {

    public static People findPeopleByname(String name) {
        People flag = null;
        for (People people : peoplelist) {
            if(people.getName().equals(name)) {
                flag = people;
            }
        }
        return flag;

    }

    public static People findPeopleByid(String id) {
        People flag = null;
        for (People people : peoplelist) {
            if(people.getnumber().equals(id)) {
                flag = people;
            }
        }
        return flag;

    }
     
    private static ArrayList<People> agenear(int yourage) {
        // TODO Auto-generated method stub
        int j=0,min=53,d_value=0,k = 0;
        ArrayList<People> plist = new ArrayList<People>();
        for (int i = 0; i < peoplelist.size(); i++) {
            d_value = peoplelist.get(i).getage() > yourage ? 
                    peoplelist.get(i).getage() - yourage : yourage - peoplelist.get(i).getage() ;
            k = d_value < min ? i : k;
            min = d_value < min ? d_value : min;
        }
        for(People people : peoplelist) {
            if(people.getage() == peoplelist.get(k).getage()) {
                plist.add(people);
            }
        }
        return plist;
    }

    private static ArrayList<People> peoplelist; 
    
    public static void main(String[] args) {
        peoplelist = new ArrayList<People>();
        Scanner scanner = new Scanner(System.in);
        File file = new File("D:\身份证号.txt");
        try {
            FileInputStream files = new FileInputStream(file);
            BufferedReader in = new BufferedReader(new InputStreamReader(files));
            String temp = null;
            while ((temp = in.readLine()) != null) {
                
                String[] information = temp.split("[ ]+");
                People people = new People();
                people.setName(information[0]);
                people.setnumber(information[1]);
                int A = Integer.parseInt(information[3]);
                people.setage(A);
                people.setsex(information[2]);
                for(int j = 4; j<information.length;j++) {
                    people.setplace(information[j]);
                }
                peoplelist.add(people);

            }
        } catch (FileNotFoundException e) {
            System.out.println("文件未找到");
            e.printStackTrace();
        } catch (IOException e) {
            System.out.println("文件读取错误");
            e.printStackTrace();
        }//捕获异常
        boolean isTrue = true;
        while (isTrue) {

            System.out.println("******************************************");
            System.out.println("   1.按姓名典序输出人员信息");
            System.out.println("   2.查询最大年龄人员信息");
            System.out.println("   3.查询最小年龄人员信息");
            System.out.println("   4.输入你的年龄,查询身份证号.txt中年龄与你最近的人");
            System.out.println("   5.查询人员中是否有你的同乡");
            System.out.println("   6.退出");
            System.out.println("******************************************");
            int nextInt = scanner.nextInt();
            switch (nextInt) {
            case 1:
                Collections.sort(peoplelist);
                System.out.println(peoplelist.toString());
                break;
            case 2:
                int max=0;
                int j,k1 = 0;
                for(int i=1;i<peoplelist.size();i++)
                {
                    j = peoplelist.get(i).getage();
                   if(j>max)
                   {
                       max = j; 
                       k1 = i;
                   }
                  
                }  
                System.out.println("年龄最大:"+peoplelist.get(k1));
                break;
            case 3:
                int min = 100;
                int j1,k2 = 0;
                for(int i=1;i<peoplelist.size();i++)
                {
                    j1 = peoplelist.get(i).getage();
                    if(j1<min)
                    {
                        min = j1; 
                        k2 = i;
                    }

                 } 
                System.out.println("年龄最小:"+peoplelist.get(k2));
                break;
            case 4:
                System.out.println("年龄:");
                int input_age = scanner.nextInt();
                ArrayList<People> plist = new ArrayList<People>();
                plist = agenear(input_age);
                for(People people : plist) {
                    System.out.println(people.toString());
                }
                break;
            case 5:
                System.out.println("请输入省份");
                String find = scanner.next();        
                for (int i = 0; i <peoplelist.size(); i++) 
                {
                    String [] place = peoplelist.get(i).getplace().split("	");
                    for(String temp : place) {
                        if(find.equals(temp)) {
                            System.out.println("你的同乡是    "+peoplelist.get(i));
                            break;
                        }
                    }
                    
                } 
                break;
            case 6:
                isTrue = false;
                System.out.println("byebye!");
                break;
            default:
                System.out.println("输入有误");
            }
        }
    }

}
package IDcard;

public class People implements Comparable<People> {

    private    String name = null;
    private    String number = null;
    private    int age = 0;
    private    String sex = null;
    private    String place = null;

    public String getName()
    {
        return name;
    }
    public void setName(String name) 
    {
        this.name = name;
    }
    public String getnumber() 
    {
        return number;
    }
    public void setnumber(String number)
    {
        this.number = number;
    }
    public int getage() 
    {
        return age;
    }
    public void setage(int age ) 
    {
        this.age = age;
    }
    public String getsex() 
    {
        return sex;
    }
    public void setsex(String sex ) 
    {
        this.sex = sex;
    }
    public String getplace() 
    {
        return place;
    }
    public void setplace(String place) 
    {
        if(this.place == null) {
            this.place = place;
        }else {
            this.place = this.place+ "	" +place;
        }

    }
    public int compareTo(People o)
    {
        return this.name.compareTo(o.getName());
    }
    public String toString() 
    {
        return  name+"	"+sex+"	"+age+"	"+number+"	"+place+"
";
    }
}

练习2

l 编写一个计算器类,可以完成加、减、乘、除的操作;

l 利用计算机类,设计一个小学生100以内数的四则运算练习程序,由计算机随机产生10道加减乘除练习题,学生输入答案,由程序检查答案是否正确,每道题正确计10分,错误不计分,10道题测试结束后给出测试总分;

l 将程序中测试练习题及学生答题结果输出到文件,文件名为test.txt

l 在以上程序适当位置加入异常捕获代码。

package 练习2;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Scanner;

public class Suanshu1 {
    public static void main(String[] args) {

        Scanner in = new Scanner(System.in);
        Suanshu Suanshu=new Suanshu();
        PrintWriter output = null;
        try {
            output = new PrintWriter("ss.txt");
        } catch (Exception e) {
            //e.printStackTrace();
        }
        int sum = 0;

        for (int i = 1; i < 11; i++) {
            int a = (int) Math.round(Math.random() * 100);
            int b = (int) Math.round(Math.random() * 100);
            int s = (int) Math.round(Math.random() * 3);

            
           switch(s)
           {
           case 1:
               System.out.println(i+": "+a+"/"+b+"=");
               while(b==0){  
                   b = (int) Math.round(Math.random() * 100); 
                   }
               double c = in.nextDouble();
               output.println(a+"/"+b+"="+c);
               if (c == Suanshu.chu_fa(a, b)) {
                   sum += 10;
                   System.out.println("恭喜答案正确");
               }
               else {
                   System.out.println("抱歉,答案错误");
               }
            
               break;
            
           case 2:
               System.out.println(i+": "+a+"*"+b+"=");
               int c1 = in.nextInt();
               output.println(a+"*"+b+"="+c1);
               if (c1 == Suanshu.chen_fa(a, b)) {
                   sum += 10;
                   System.out.println("恭喜答案正确");
               }
               else {
                   System.out.println("抱歉,答案错误");
               }
               break;
           case 3:
               System.out.println(i+": "+a+"+"+b+"=");
               int c2 = in.nextInt();
               output.println(a+"+"+b+"="+c2);
               if (c2 == Suanshu.jia_fa(a, b)) {
                   sum += 10;
                   System.out.println("恭喜答案正确");
               }
               else {
                   System.out.println("抱歉,答案错误");
               }
               
               break ;
           case 4:
               System.out.println(i+": "+a+"-"+b+"=");
               int c3 = in.nextInt();
               output.println(a+"-"+b+"="+c3);
               if (c3 == Suanshu.jian_fa(a, b)) {
                   sum += 10;
                   System.out.println("恭喜答案正确");
               }
               else {
                   System.out.println("抱歉,答案错误");
               }
               break ;

               } 
    
          }
        System.out.println("成绩"+sum);
        output.println("成绩:"+sum);
        output.close();
         
    }
}
package 练习2;

public class Suanshu
{
       private int a;
       private int b;
        public int  jia_fa(int a,int b)
        {
            return a+b;
        }
        public int   jian_fa(int a,int b)
        {
            if((a-b)<0)
                return 0;
            else
            return a-b;
        }
        public int   chen_fa(int a,int b)
        {
            return a*b;
        }
        public int   chu_fa(int a,int b)
        {
            if(b!=0)
            return a/b;    
            else
        return 0;
        }

        
}

实验结果如下图所示:

 

实验4:断言、日志、程序调试技巧验证实验。

实验程序1

//断言程序示例

public class AssertDemo {

    public static void main(String[] args) {        

        test1(-5);

        test2(-3);

    }

    

    private static void test1(int a){

        assert a > 0;

        System.out.println(a);

    }

    private static void test2(int a){

       assert a > 0 : "something goes wrong here, a cannot be less than 0";

        System.out.println(a);

    }

}

l 在elipse下调试程序AssertDemo,结合程序运行结果理解程序;

l 注释语句test1(-5);后重新运行程序,结合程序运行结果理解程序;

l 掌握断言的使用特点及用法。

实验结果如下图所示:

注释后程序如下

 package _pasted_code_;
//断言程序示例
public class AssertDemo {
    public static void main(String[] args) {        

        //test1(-5);

        test2(-3);

    }

    

    private static void test1(int a){

        assert a > 0;

        System.out.println(a);

    }

    private static void test2(int a){

       assert a > 0 : "something goes wrong here, a cannot be less than 0";

        System.out.println(a);

    }

}

实验结果如下图所示:

实验程序2:

l 用JDK命令调试运行教材298-300页程序7-2,结合程序运行结果理解程序;

l 并掌握Java日志系统的用途及用法。

package logging;

import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.logging.*;
import javax.swing.*;

/**
 * A modification of the image viewer program that logs various events.
 * @version 1.03 2015-08-20
 * @author Cay Horstmann
 */
public class LoggingImageViewer
{
   public static void main(String[] args)
   {
      if (System.getProperty("java.util.logging.config.class") == null
            && System.getProperty("java.util.logging.config.file") == null)
      {
         try
         {
            Logger.getLogger("com.horstmann.corejava").setLevel(Level.ALL);
            final int LOG_ROTATION_COUNT = 10;
            Handler handler = new FileHandler("%h/LoggingImageViewer.log", 0, LOG_ROTATION_COUNT);
            Logger.getLogger("com.horstmann.corejava").addHandler(handler);
         }
         catch (IOException e)
         {
            Logger.getLogger("com.horstmann.corejava").log(Level.SEVERE,
                  "Can't create log file handler", e);
         }
      }

      EventQueue.invokeLater(() ->
            {
               Handler windowHandler = new WindowHandler();
               windowHandler.setLevel(Level.ALL);
               Logger.getLogger("com.horstmann.corejava").addHandler(windowHandler);

               JFrame frame = new ImageViewerFrame();
               frame.setTitle("LoggingImageViewer");
               frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

               Logger.getLogger("com.horstmann.corejava").fine("Showing frame");
               frame.setVisible(true);
            });
   }
}

/**
 * The frame that shows the image.
 */
class ImageViewerFrame extends JFrame
{
   private static final int DEFAULT_WIDTH = 300;
   private static final int DEFAULT_HEIGHT = 400;   

   private JLabel label;
   private static Logger logger = Logger.getLogger("com.horstmann.corejava");

   public ImageViewerFrame()
   {
      logger.entering("ImageViewerFrame", "<init>");      
      setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);

      // 设置菜单栏
      JMenuBar menuBar = new JMenuBar();
      setJMenuBar(menuBar);

      JMenu menu = new JMenu("File");
      menuBar.add(menu);

      JMenuItem openItem = new JMenuItem("Open");
      menu.add(openItem);
      openItem.addActionListener(new FileOpenListener());

      JMenuItem exitItem = new JMenuItem("Exit");
      menu.add(exitItem);
      exitItem.addActionListener(new ActionListener()
         {
            public void actionPerformed(ActionEvent event)
            {
               logger.fine("Exiting.");
               System.exit(0);
            }
         });

      // 使用标签显示图像
      label = new JLabel();
      add(label);
      logger.exiting("ImageViewerFrame", "<init>");
   }

   private class FileOpenListener implements ActionListener
   {
      public void actionPerformed(ActionEvent event)
      {
         logger.entering("ImageViewerFrame.FileOpenListener", "actionPerformed", event);

         // 设置文件选择器
         JFileChooser chooser = new JFileChooser();
         chooser.setCurrentDirectory(new File("."));

         // 接受所有以.gif结尾的文件
         chooser.setFileFilter(new javax.swing.filechooser.FileFilter()
            {
               public boolean accept(File f)
               {
                  return f.getName().toLowerCase().endsWith(".gif") || f.isDirectory();
               }

               public String getDescription()
               {
                  return "GIF Images";
               }
            });

         // 显示文件选择器对话框
         int r = chooser.showOpenDialog(ImageViewerFrame.this);

         // 如果图像文件被接受,将其设置为标签的图标
         if (r == JFileChooser.APPROVE_OPTION)
         {
            String name = chooser.getSelectedFile().getPath();
            logger.log(Level.FINE, "Reading file {0}", name);
            label.setIcon(new ImageIcon(name));
         }
         else logger.fine("File open dialog canceled.");
         logger.exiting("ImageViewerFrame.FileOpenListener", "actionPerformed");
      }
   }
}

/**
 * A handler for displaying log records in a window.
 */
class WindowHandler extends StreamHandler
{
   private JFrame frame;

   public WindowHandler()
   {
      frame = new JFrame();
      final JTextArea output = new JTextArea();
      output.setEditable(false);
      frame.setSize(200, 200);
      frame.add(new JScrollPane(output));
      frame.setFocusableWindowState(false);
      frame.setVisible(true);
      setOutputStream(new OutputStream()
         {
            public void write(int b)
            {
            } // 不调用

            public void write(byte[] b, int off, int len)
            {
               output.append(new String(b, off, len));
            }
         });
   }

   public void publish(LogRecord record)
   {
      if (!frame.isVisible()) return;
      super.publish(record);
      flush();
   }
}

运行结果如下图所示:

实验程序3:

l 用JDK298-300页程序7-2,结合程序运行结果理解程序;

l 按课件66-77内容练习并掌握Elipse的常用调试技术。

1、断点:

(1)条件断点:就是一个有一定条件的断点,只有满足了用户设置的条件,代码才会在运行到断点处停止。

(2)变量断点:在变量的值初始化或是变量值改变时可以停止,当然变量断点上也是可以加条件的。

(3)方法断点:方法断y点的特别之处在于它可以打开JDK的源代码里,由于JDK在编译时去掉了调试信息,所以普通断点是不能打到里面的,但方法断点却可以。

(4)异常断点:经常遇到一些异常,然后程序就退出来了,要找到异常发生的地方就比较难了,还好可以打一个异常断点。

2、捕获异常:try、catch、finally块

Try语句:括住可能抛出异常的代码段

Catch语句:指明要捕获的异常及相应的处理代码

Finally语句:必须执行的程序块

3、断言:是程序的开发和测试阶段用于插入一些代码错误检测语句的工具。

4、assert 条件和assert 条件:表达式

这两个形式都会对布尔“条件”进行判断,如果判断结果为假(false),说明程序已经处于不正确的状态下,系统则抛出AssertionError,给出警告并且退出。在第二种形式中,“表达式”会传入AssertionError的构造函数中并转成一个消息字符。

 三、实验总结

  通过本周的学习,我了解了异常及对异常出现的一些处理。了解了一些异常是程序员可处理的,一些是程序员无法处理的。通过本周的实验及课上老师和学长的讲解,使我对编程有了进一步的认识,对程序中出现的一些错误可以进行相关的处理。更好的解决问题。

原文地址:https://www.cnblogs.com/http-www-whh0601-cnblogs-com/p/9850983.html