李晓菁201771010114《面向对象程序设计(Java)》第九周学习总结

一:理论部分

1.异常

(1)在程序的执行过程中所发生的异常事件,它中断指令的正常执行。

(2)Java的异常处理机制,可以控制程序从错误产生的位置转移到能够进行错误处理的位置。

2.异常类型

(1)非致命异常:通过某种修正后程序还能继续运行。Java中提供了一种独特的处理异常机制,通过异常来处理程序设计中出现的错误。

(2)致命异常:程序遇到了非常严重的不正常状态,不能简单恢复运行,这种错误程序本身无法解决。

Java中的所有异常都可以间接地继承与throwable类,除内置异常类外,程序员可自定义异常类。

(1)Error:很难恢复的异常错误,一般不由程序处理。

(2)Expection类:

①RuntimeExpection:程序设计或实现上的问题,如数组越界等。(一定是程序员的问题)

②其他异常:通常是由环境因素引起的,并且可以被处理,如文件不存在等。

(3)未检查异常:Java将派生于error类或runtimeExpection类的所有异常称为未检查异常,编译器允许不对它们做出异常处理。

(4)已检查异常:非运行时异常,程序本身没有什么问题,但由于某种情况的变化,程序不能正常运行,导致异常出现。

RuntimeExpection类:运行时异常类。

IOExpection类:输入输出异常。

3.异常声明:声明抛出(已检查)异常:如果一个方法可能会生成一些异常,但是该方法并不确切知道如何对这些异常进行处理,这时,

这些方法就需要声明抛出这些异常。(用throws来声明)

throws语句可同时指明多个异常,说明该方法将不对这些异常做处理,而是声明抛出他们。

4.异常抛出

首先决定抛出异常类型,对于已存在的异常类,抛出该类的异常对象:(1)找到合适的异常类(2)创建这个类的一个对象(3)将该对象抛出

一个方法抛出后,他就不能返回调用者了。

5.异常捕获:程序运行期间,异常发生时,Java运行系统从异常生成的代码块开始,寻找相应的异常处理代码,并将异常交给该方法处理。

某个异常发生时,若程序没有在任何地方进行该异常的捕获,则程序就会终止运行,并在控制台上输出异常信息。

6.异常处理技术:(1)积极处理技术:try{    }catch{  }语句

(2)消极处理方式:throws语句

二;实验部分

实验九 异常、断言与日志

实验时间 2018-10-25

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();

      }

}

package 第九周;

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

package 第九周;
import java.io.*;
public class ExceptionDemo2 {
    public static void main(String args[]) throws IOException //抛出异常的类型可由父类Expection直接抛出
    {
         FileInputStream fis=new FileInputStream("text.txt");//JVM自动生成异常对象
         
         int b;
         while((b=fis.read())!=-1)
         {
             System.out.print(b);
         }
         fis.close();
     }
}
demo2

经过异常处理后输出为字节流

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

测试程序1:

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

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

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

package stackTrace;

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();//调用throwable类的方法
      StackTraceElement[] frames = t.getStackTrace();//使用getStrackTrace方法,会得到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);
   }
}
stackTrance

测试程序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");

       }

       catchFileNotFoundExcption 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;
public class ExceptionTest {
    public static void main (String args[])
       {
           try{
               FileInputStream fis=new FileInputStream("身份证号.txt");
               BufferedReader in = new BufferedReader(new InputStreamReader(fis));
                String m, n = new String();
                while ((m = in.readLine()) != null) {
                    n += m + "\n ";
                }
                in.close();
                System.out.println(n);

            } catch (FileNotFoundException e) {
                System.out.println("所找信息文件找不到");
                e.printStackTrace();
            } catch (IOException e) {
                System.out.println("所找信息文件读取错误");
                e.printStackTrace();
            }
        }
    }
积极处理方法

 

package 第九周;
import java.io.*;
public class ExceptionTest {
    public static void main (String args[]) throws IOException
       {
          
               FileInputStream fis=new FileInputStream("身份证号.txt");
               BufferedReader in = new BufferedReader(new InputStreamReader(fis));
                String m, n = new String();
                while ((m = in.readLine()) != null) {
                    n += m + "\n ";
                }
                in.close();
                System.out.println(n);

            } //catch (FileNotFoundException e) {
               // System.out.println("所找信息文件找不到");
                //e.printStackTrace();
            //} catch (IOException e) {
             //   System.out.println("所找信息文件读取错误");
               // e.printStackTrace();
            //}
        }
//    }
消极处理

 

 

实验3: 编程练习

练习1

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

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

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

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

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

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

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

package text8;

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.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;

public class Xinxi {
    private static ArrayList<Student> studentlist;

    
    public static  void main(String[] args) {
        studentlist = new ArrayList<>();
        Scanner scanner = new Scanner(System.in);
        File file = new File("D:\\身份证号\\身份证号.txt");
        try {
            FileInputStream fis = new FileInputStream(file);
            BufferedReader in = new BufferedReader(new InputStreamReader(fis));
            String temp = null;
            while ((temp = in.readLine()) != null) {

                Scanner linescanner = new Scanner(temp);

                linescanner.useDelimiter(" ");
                String name = linescanner.next();
                String number = linescanner.next();
                String sex = linescanner.next();
                String age = linescanner.next();
                String province = linescanner.nextLine();
                Student student = new Student();
                student.setName(name);
                student.setnumber(number);
                student.setsex(sex);
                int a = Integer.parseInt(age);
                student.setage(a);
                student.setprovince(province);
                studentlist.add(student);

            }
        } catch (FileNotFoundException e) {//添加的异常处理语句try{   }catch{   }语句
            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.寻找老乡");

            System.out.println("5.退出");
            String n = scanner.next();
            switch (n) {
            case "1":
                Collections.sort(studentlist);
                System.out.println(studentlist.toString());
                break;
            case "2":
                int max = 0, min = 100;
                int j, k1 = 0, k2 = 0;
                for (int i = 1; i < studentlist.size(); i++) {
                    j = studentlist.get(i).getage();
                    if (j > max) {
                        max = j;
                        k1 = i;
                    }
                    if (j < min) {
                        min = j;
                        k2 = i;
                    }

                }
                System.out.println("年龄最大:" + studentlist.get(k1));

                System.out.println("年龄最小:" + studentlist.get(k2));
                break;
            case "3":
                System.out.println("家乡在哪里?");
                String find = scanner.next();
                String place = find.substring(0, 3);
                for (int i = 0; i < studentlist.size(); i++) {
                    if (studentlist.get(i).getprovince().substring(1, 4).equals(place))
                        System.out.println("同乡" + studentlist.get(i));
                }
                break;

            case "4":
                System.out.println("年龄:");
                int yourage = scanner.nextInt();
                int near = agenear(yourage);
                int value = yourage - studentlist.get(near).getage();
                System.out.println("" + studentlist.get(near));
                break;
            case "5":
                isTrue = false;
                System.out.println("退出程序!");
                break;
            default:
                System.out.println("输入有误");

            }
        }
    }

    public static int agenear(int age) {
        int j = 0, min = 53, value = 0, flag = 0;
        for (int i = 0; i < studentlist.size(); i++) {
            value = studentlist.get(i).getage() - age;
            if (value < 0)
                value = -value;
            if (value < min) {
                min = value;
                flag = i;
            }
        }
        return flag;
    }

}
xinxi
package text8;

public  class Student implements Comparable<Student> {

    private String name;
    private String number;
    private String sex;
    private String province;
    private int age;

    public void setName(String name) {
        // TODO 自动生成的方法存根
        this.name = name;

    }

    public String getName() {
        // TODO 自动生成的方法存根
        return name;
    }

    public void setnumber(String number) {
        // TODO 自动生成的方法存根
        this.number = number;
    }

    public String getNumber() {
        // TODO 自动生成的方法存根
        return number;
    }

    public void setsex(String sex) {
        // TODO 自动生成的方法存根
        this.sex = sex;
    }

    public String getsex() {
        // TODO 自动生成的方法存根
        return sex;
    }

    public void setprovince(String province) {
        // TODO 自动生成的方法存根
        this.province = province;
    }

    public String getprovince() {
        // TODO 自动生成的方法存根
        return province;
    }

    public void setage(int a) {
        // TODO 自动生成的方法存根
        this.age = age;
    }

    public int getage() {
        // TODO 自动生成的方法存根
        return age;
    }

    public int compareTo(Student o) {
        return this.name.compareTo(o.getName());
    }

    public String toString() {
        return name + "\t" + sex + "\t" + age + "\t" + number + "\t" + province + "\n";
    }
}
student类

注:以下实验课后完成

练习2

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

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

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

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

 

package 第九周;
import java.util.Random;
import java.util.Scanner;
import java.io.FileNotFoundException;
import java.io.PrintWriter;

    public class Demo {
        public static void main(String[] args) {
            // 用户的答案要从键盘输入,因此需要一个键盘输入流
            //Scanner in = new Scanner(System.in);
            yunsuan counter = new yunsuan  ();
            PrintWriter out = null;
            
            try {
                out = new PrintWriter("D:\\text.txt");
            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            int sum = 0;
            // 通过循环生成10道题
            for (int i = 0; i < 10; i++) {
            
                
                int a = (int) Math.round(Math.random() * 10);
                int b = (int) Math.round(Math.random() * 10);
                
                Scanner in1 =new Scanner(System.in);
                
                
                switch((int)(Math.random()*4))
                
                {
                
                case 1:
                System.out.println( ""+a+"+"+b+"=");
                
                int c1 = in1.nextInt();
                out.println(a+"+"+b+"="+c1);
                if (c1 == counter.add(a, b)) {
                    sum += 10;
                    System.out.println("恭喜答案正确");
                }
                else {
                    System.out.println("抱歉答案错误");
                }
                
                break ;
                case 2:
                System.out.println(i + ": " + a + "-" + b + "=");
                int c2 = in1.nextInt();
                out.println(a + "-" + b + "=" + c2);
                if (c2 == counter.reduce(a, b)) {
                    sum += 10;
                    System.out.println("恭喜答案正确");
                } else {
                    System.out.println("抱歉答案错误");
                }
                break;
                case 3:
                System.out.println(i + ": " + a + "*" + b + "=");
                int c3 = in1.nextInt();
                out.println(a + "*" + b + "=" + c3);
                if (c3 == counter.multiplication(a, b)) {
                    sum += 10;
                    System.out.println("恭喜答案正确");
                } else {
                    System.out.println("抱歉答案错误");
                }
                break;
                case 4:
                System.out.println(""+a+"/"+b+"=");
                while(b==0)
                {  b = (int) Math.round(Math.random() * 100);
                }
             int c4= in1.nextInt();
             out.println(a+"/"+b+"="+c4);
             if (c4 == counter.devision(a, b)) {
                 sum += 10;
                 System.out.println("恭喜答案正确");
             }
             else {
                 System.out.println("抱歉答案错误");
             }
             break;
             }
            }
            
                System.out.println("总分:"+sum);
                out.println(sum);
                
                out.close();
                }
                }
    

            
            
demo
package 第九周;

public class yunsuan {

    public int multiplication(int a, int b) {
        // TODO 自动生成的方法存根
        return a*b;
    }

    public int add(int a, int b) {
        // TODO 自动生成的方法存根
        return a+b;
    }

    public int reduce(int a, int b) {
        // TODO 自动生成的方法存根
        if((a-b)>0)
        return a-b;
        else
            return 0;
    }

    public int devision(int a, int b) {
        // TODO 自动生成的方法存根
        if(b!=0)
        return a/b;
        else
            return 0;
    }

}
yunsuan

实验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 第九周;

public class AssertDemo {
     public static void main(String[] args) {        
           // test1(-5);
            test2(-3);
        }
        
        private static void test1(int a){
            assert a > 0;//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);
        }
}
Assertdemo

实验程序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);

      // set up menu bar
      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);
            }
         });

      // use a label to display the images
      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);

         // set up file chooser
         JFileChooser chooser = new JFileChooser();
         chooser.setCurrentDirectory(new File("."));

         // accept all files ending with .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";
               }
            });

         // show file chooser dialog
         int r = chooser.showOpenDialog(ImageViewerFrame.this);

         // if image file accepted, set it as icon of the label
         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)
            {
            } // not called

            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();
   }
}
logging

实验程序3:

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

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

 

三:实验总结;通过本周的理论知识学习以及结合实验课程,主要掌握了异常的概念以及对于异常的处理机制,学到了两种对于异常的处理方法,

积极处理机器语句的定义;消极处理及其语句的含义。并在自己的程序中加入异常处理的代码部分,且理解它存在的含义和与之对应的异常捕获是捕获哪个部分。

posted @ 2018-10-28 16:14  是木子呀  阅读(137)  评论(0编辑  收藏  举报