201871010111-刘佳华《面向对象程序设计(java)》第十周学习总结

201871010111-刘佳华《面向对象程序设计(java)》第十周学习总结

实验八 异常、断言与日志

实验时间 2019-11-1

1、实验目的与要求

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

(2) 了解断言的用法;

(3) 了解日志的用途;

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

一:理论部分。

错误类型:1)用户输入错误;2)设备错误;3)物理限制;4)代码错误

1.异常:在程序的执行过程中所发生的异常事件,它中断指令的正常执行。异常对象都是派生于Throwable类的一个实例。

所有异常类都是由Throwable继承而来,在下一层分解为两个支:Error(致命错误)和Exception(非致命错误)。

设计java程序时,关注Exception层次结构。Exception层次结构又分解为两个分支:一个分支派生于RuntimeException;另一个分支包含其他异常。RuntimeException为运行时异常类,一般是程序错误产生。

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

1)错误的类型转换

2)数组访问越界

 3)访问空指针

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

2.抛出异常:声明抛出异常在方法声明中用throws子句中来指明。

1)throws子句可以同时指明多个异常,说明该方法将不对这些异常进行处理,而是声明抛出它们。

2)一个方法必须声明该方法所有可能抛出的已检查异常,而未检查异常要么不可控制(Error),要么应该避免发生(RuntimeException)。如果方法没有声明所有可能发生的已检查异常,编译器会给出一个错误消息。

3)抛出异常对象通过throw语句来实现。

3.创建异常类

自定义异常类:定义一个派生于Exception的直接或间接子类。如一个派生于IOException的类。

4.捕获异常

1)捕获异常的第一步是用try{}子句选定捕获异常的代码范围,由try所限定的代码块中的语句在执行过程中可能会自动生成异常对象并抛出。

2)catch子句:catch块是对异常对象进行处理的代码;

a.每个try代码块可以伴随一个或多个catch语句,用于处理try代码块中所生成的各类异常事件;

b.catch语句只需要一个形式参数指明它所能捕获的异常类对象,这个异常类必须是Throwable的子类,运行时系统通过参数值把被抛出的异常对象传递给catch块;

c.catch块可以通过异常对象调用类Throwable。

getMessage:用来得到有关异常事件的信息;

printStackTrace:用来跟踪异常事件发生时执行堆栈的内容。

5.堆栈跟踪:程序执行中一个方法调用过程的列表,它包含了程序执行过程中方法调用的特定位置。

6.程序编码时异常处理的两种方式:

1)积极处理方式:确切知道如何处理的异常应该捕获;

2)消极处理方式:不知道如何去处理的异常声明抛出。

5.断言

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

断言(assert)语法如下

1、assert 条件

或者

2、assert 条件:表达式

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

2、实验内容和步骤

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

//异常示例1
public class ExceptionDemo1 {
	public static void main(String args[]) {
		int a = 0;
		System.out.println(5 / a);
	}
}

运行截图如下:

因分母为零,程序在运行过程中出现异常。修改后程序如下:

修改后代码:

 1 package TEST01;
 2 
 3 import java.util.Scanner;
 4 
 5 public class ExceptionDemo1 {
 6     public static void main(String args[]) {
 7          Scanner in = new Scanner(System.in);
 8          int a =in.nextInt();
 9         if (a==0) {
10             System.out.println("input error!");
11         }
12         else
13         System.out.println(5 / a);
14         in.close();
15     }
16 }
ExceptionDemo1

运行截图:

//异常示例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.用抛出异常方法修改后程序如下:

 1 package TEST01;
 2 //异常示例2
 3 import java.io.*;
 4 
 5 public class ExceptionDemo2 {
 6     public static void main(String args[]) throws IOException 
 7      {
 8           FileInputStream fis=new FileInputStream("text.txt");//JVM自动生成异常对象
 9           int b;
10           while((b=fis.read())!=-1)
11           {
12               System.out.print(b);
13           }
14           fis.close();
15       }
16 }
ExceptionDemo2 

2.将可能出错代码放入try子句中程序修改后如下:

 1 package TEST01;
 2 import java.io.*;
 3 
 4 public class ExceptionDemo2 {
 5     public static void main(String args[]) 
 6      {
 7           FileInputStream fis = null;
 8         try {
 9             fis = new FileInputStream("text.txt");
10         } catch (FileNotFoundException e) {
11             // TODO Auto-generated catch block
12             e.printStackTrace();
13         }//JVM自动生成异常对象
14           int b;
15           try {
16             while((b=fis.read())!=-1)
17               {
18                   System.out.print(b);
19               }
20         } catch (IOException e) {
21             // TODO Auto-generated catch block
22             e.printStackTrace();
23         }
24           try {
25             fis.close();
26         } catch (IOException e) {
27             // TODO Auto-generated catch block
28             e.printStackTrace();
29         }
30       }
31 }
ExceptionDemo2

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

测试程序1:

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

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

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

 1 package stackTrace;
 2 
 3 import java.util.*;
 4 
 5 /**
 6  * A program that displays a trace feature of a recursive method call.
 7  * @version 1.10 2017-12-14
 8  * @author Cay Horstmann
 9  */
10 public class StackTraceTest
11 {
12    /**
13     * Computes the factorial of a number
14     * @param n a non-negative integer
15     * @return n! = 1 * 2 * . . . * n
16     */
17    public static int factorial(int n)//求阶乘
18    {
19       System.out.println("factorial(" + n + "):");//调用factorial函数
20       var walker = StackWalker.getInstance();//创建一个表示指定执行点的堆栈跟踪元素
21       walker.forEach(System.out::println);      
22       int r;
23       if (n <= 1) r = 1;
24       else r = n * factorial(n - 1);//计算n个数的阶乘需要调用之前n-1个数的阶乘
25       System.out.println("return " + r);
26       return r;
27    }
28 
29    public static void main(String[] args)
30    {
31       try (var in = new Scanner(System.in))
32       {
33          System.out.print("Enter n: ");
34          int n = in.nextInt();
35          factorial(n);
36       }
37    }
38 }
StackTraceTest

 运行结果:

测试程序2:

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

l 下列两个简单程序范例给出了两种异常处理的代码格式。在elipse IDE中编辑、调试运行源程序ExceptionTest.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");

     }

}

积极的处理方式:

 1 package TEST01;
 2 
 3 import java.io.*;
 4 
 5 public class ExceptionTest {
 6     public static void main (String args[])
 7    {
 8        try{
 9            
10            FileInputStream fis=new FileInputStream("身份证号.txt");
11            BufferedReader in =new BufferedReader(new InputStreamReader(fis));
12            String m=new String();
13            String n=new String();
14            while((m=in.readLine())!=null) {
15                n+=m+"\n";
16            }
17            in.close();
18            System.out.println(n);
19 
20        }
21        catch(FileNotFoundException e) {
22            System.out.println("文件未找到");
23            e.printStackTrace();
24        }catch(IOException e) {
25            System.out.println("学生信息错误");
26            e.printStackTrace();
27        }
28     
29     }
30 }
ExceptionTest

消极的处理方式:

 1 import java.io.*;
 2 public class ExceptionTest {
 3     public static void main (String args[]) throws  IOException
 4      {
 5          FileInputStream fis=new FileInputStream("身份证号.txt");
 6         BufferedReader in = new BufferedReader(new InputStreamReader(fis));
 7        String m, n = new String();
 8        while ((m = in.readLine()) != null) {
 9            n += m + "\n ";
10        }
11        in.close();
12        System.out.println(n);
13      }
14 }
ExceptionTest

运行截图:

实验3: 编程练习

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

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

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

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

 分析:

 代码如下:

 1 import java.io.FileNotFoundException;
 2 import java.io.PrintWriter;
 3 import java.util.Scanner;
 4 
 5 public class Jisuanqi {
 6 
 7     public static void main(String[] args) {
 8         
 9         Scanner in=new Scanner(System.in);
10         JsQ jsq=new JsQ();
11         PrintWriter output = null;
12         try {
13              output = new PrintWriter("题目.txt");
14          } catch (FileNotFoundException e) {
15              e.printStackTrace();
16          }
17         int sum = 0;
18         
19         for(int i=0;i<10;i++) {
20             int s = (int) Math.round(Math.random() * 3);
21             int a = (int) Math.round(Math.random() * 100);
22             int b = (int) Math.round(Math.random() * 100);
23             switch(s)
24             {
25             case 0:
26                 System.out.println( a + "/" + b + "=");
27                 while (b == 0) {
28                     b = (int) Math.round(Math.random() * 100);
29                 }
30                 double c3 = in.nextDouble();
31                 output.println(a + "/" + b + "=" + c3);
32                 if (c3 ==jsq.CHUF(a, b) ) {
33                     sum += 10;
34                     System.out.println("恭喜你,答对了!");
35                 } else {
36                     System.out.println("抱歉,答错了!");
37                 }
38                 break;
39             case 1:
40                 System.out.println( a + "-" + b + "=");
41                 double c1 = in.nextDouble();
42                 output.println(a + "-" + b + "=" + c1);
43                 if (c1 ==jsq.GF(a, b) ) {
44                     sum += 10;
45                     System.out.println("恭喜你,答对了!");
46                 } else {
47                     System.out.println("抱歉,答错了!");
48                 }
49                 break;
50             case 2:
51                 System.out.println( a + "*" + b + "=");
52                 double c2 = in.nextDouble();
53                 output.println(a + "*" + b + "=" + c2);
54                 if (c2 ==jsq.CHEF(a, b) ) {
55                     sum += 10;
56                     System.out.println("恭喜你,答对了!");
57                 } else {
58                     System.out.println("抱歉,答错了!");
59                 }
60                 break;
61             case 3:
62                 System.out.println( a + "+" + b + "=");
63                 double c0 = in.nextDouble();
64                 output.println(a + "+" + b + "=" + c0);
65                 if (c0 ==jsq.JF (a, b)) {
66                     sum += 10;
67                     System.out.println("恭喜你,答对了!");
68                 } else {
69                     System.out.println("抱歉,答错了!");
70                 }
71                 break;
72             }
73             
74         }
75         System.out.println("你的得分为:"+sum);
76         output.println("你的得分为:"+sum);
77         output.close();
78         in.close();
79     }
80     
81 }
Jisuanqi
 1 class JsQ{
 2     private int a;
 3     private int b;
 4     
 5     /*public  JsQ(int a,int b ){
 6         this.a=a;
 7         this.b=b;
 8         
 9     }*/
10     public double JF(int a,int b) {
11         
12         return (a+b);
13     }
14     public double GF(int a,int b) {
15         return (a-b);
16     }
17     
18     public double CHEF(int a,int b) {
19         return (a*b);
20     }
21     public double CHUF(int a,int b) {
22         return (a/b);
23     }
24 }
JsQ

运行结果如下:

存入文件:

实验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 掌握断言的使用特点及用法。

小结:

1、assert 条件

或者

2、assert 条件:表达式

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

实验程序2:

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

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

  1 package logging;
  2 
  3 import java.awt.*;
  4 import java.awt.event.*;
  5 import java.io.*;
  6 import java.util.logging.*;
  7 import javax.swing.*;
  8 
  9 /**
 10  * A modification of the image viewer program that logs various events.
 11  * @version 1.03 2015-08-20
 12  * @author Cay Horstmann
 13  */
 14 public class LoggingImageViewer
 15 {
 16    public static void main(String[] args)
 17    {
 18       if (System.getProperty("java.util.logging.config.class") == null
 19             && System.getProperty("java.util.logging.config.file") == null)
 20       {
 21          try
 22          {
 23             Logger.getLogger("com.horstmann.corejava").setLevel(Level.ALL);
 24             final int LOG_ROTATION_COUNT = 10;
 25             var handler = new FileHandler("%h/LoggingImageViewer.log", 0, LOG_ROTATION_COUNT);
 26             Logger.getLogger("com.horstmann.corejava").addHandler(handler);
 27          }
 28          catch (IOException e)
 29          {
 30             Logger.getLogger("com.horstmann.corejava").log(Level.SEVERE,
 31                "Can't create log file handler", e);
 32          }
 33       }
 34 
 35       EventQueue.invokeLater(() ->
 36             {
 37                var windowHandler = new WindowHandler();
 38                windowHandler.setLevel(Level.ALL);
 39                Logger.getLogger("com.horstmann.corejava").addHandler(windowHandler);
 40 
 41                var frame = new ImageViewerFrame();
 42                frame.setTitle("LoggingImageViewer");
 43                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 44 
 45                Logger.getLogger("com.horstmann.corejava").fine("Showing frame");
 46                frame.setVisible(true);
 47             });
 48    }
 49 }
 50 
 51 /**
 52  * The frame that shows the image.
 53  */
 54 class ImageViewerFrame extends JFrame
 55 {
 56    private static final int DEFAULT_WIDTH = 300;
 57    private static final int DEFAULT_HEIGHT = 400;   
 58 
 59    private JLabel label;
 60    private static Logger logger = Logger.getLogger("com.horstmann.corejava");
 61 
 62    public ImageViewerFrame()
 63    {
 64       logger.entering("ImageViewerFrame", "<init>");      
 65       setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
 66 
 67       // set up menu bar
 68       var menuBar = new JMenuBar();
 69       setJMenuBar(menuBar);
 70 
 71       var menu = new JMenu("File");
 72       menuBar.add(menu);
 73 
 74       var openItem = new JMenuItem("Open");
 75       menu.add(openItem);
 76       openItem.addActionListener(new FileOpenListener());
 77 
 78       var exitItem = new JMenuItem("Exit");
 79       menu.add(exitItem);
 80       exitItem.addActionListener(new ActionListener()
 81          {
 82             public void actionPerformed(ActionEvent event)
 83             {
 84                logger.fine("Exiting.");
 85                System.exit(0);
 86             }
 87          });
 88 
 89       // use a label to display the images
 90       label = new JLabel();
 91       add(label);
 92       logger.exiting("ImageViewerFrame", "<init>");
 93    }
 94 
 95    private class FileOpenListener implements ActionListener
 96    {
 97       public void actionPerformed(ActionEvent event)
 98       {
 99          logger.entering("ImageViewerFrame.FileOpenListener", "actionPerformed", event);
100 
101          // set up file chooser
102          var chooser = new JFileChooser();
103          chooser.setCurrentDirectory(new File("."));
104 
105          // accept all files ending with .gif
106          chooser.setFileFilter(new javax.swing.filechooser.FileFilter()
107             {
108                public boolean accept(File f)
109                {
110                   return f.getName().toLowerCase().endsWith(".gif") || f.isDirectory();
111                }
112 
113                public String getDescription()
114                {
115                   return "GIF Images";
116                }
117             });
118 
119          // show file chooser dialog
120          int r = chooser.showOpenDialog(ImageViewerFrame.this);
121 
122          // if image file accepted, set it as icon of the label
123          if (r == JFileChooser.APPROVE_OPTION)
124          {
125             String name = chooser.getSelectedFile().getPath();
126             logger.log(Level.FINE, "Reading file {0}", name);
127             label.setIcon(new ImageIcon(name));
128          }
129          else logger.fine("File open dialog canceled.");
130          logger.exiting("ImageViewerFrame.FileOpenListener", "actionPerformed");
131       }
132    }
133 }
134 
135 /**
136  * A handler for displaying log records in a window.
137  */
138 class WindowHandler extends StreamHandler
139 {
140    private JFrame frame;
141 
142    public WindowHandler()
143    {
144       frame = new JFrame();
145       var output = new JTextArea();
146       output.setEditable(false);
147       frame.setSize(200, 200);
148       frame.add(new JScrollPane(output));
149       frame.setFocusableWindowState(false);
150       frame.setVisible(true);
151       setOutputStream(new OutputStream()
152          {
153             public void write(int b)
154             {
155             } // not called
156 
157             public void write(byte[] b, int off, int len)
158             {
159                output.append(new String(b, off, len));
160             }
161          });
162    }
163 
164    public void publish(LogRecord record)
165    {
166       if (!frame.isVisible()) return;
167       super.publish(record);
168       flush();
169    }
170 }
LoggingImageViewer

运行结果:

实验程序3:

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

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

1)条件断点(有一定条件的断点):在Eclipse Java 编辑区的行头双击就会得到一个断点,代码会运行到此处时停止。

在断点处点击鼠标右键,选择最后一个“Breakpoint Properties”。

2)变量断点:在变量的值初始化,或是变量值改变时可以停止。

3)方法断点:方法断点就是将断点打在方法的入口处。

4)异常断点:当异常发生时,代码会停在异常发生处。

5)重新调试:回退时,请在需要回退的线程方法上点右键,选择“Drop to Frame”。

6)单步执行程序 

7)检查变量

8)改变变量值

实验总结:

      通过本周的学习,对理论知识异常、日志、断言和调试的理论知识有了进一步的掌握,对理论知识的学习如下:

异常:程序的执行过程中所发生的异常事件,它中断指令的正常执行

Java把程序运行时可能遇到的错误分为两类:非致命异常:通过某种修正后程序还能继续执行。这类错误叫作异常。如:文件不存在、无效的数组下标、空引用、网络断开、打印机

脱机、磁盘满等。Java中提供了一种独特的处理异常的机制,通过异常来处理程序设计中出现的错误。致命异常:程序遇到了非常严重的不正常状态,不能简单恢复执行,是致命性

错误。如:内存耗尽、系统内部错误等。这种错误程序本身无法解决。而且其中还有异常的两种方式,比如说消极处理和积极处理两种方式。

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

而且使用断言必须注意两点:

 断言失败是致命的、不可恢复的错误。
断言检查仅仅用在程序开发和测试阶段
    最后在课本所给出的实例程序中我以为检测了所学到的理论知识,对最后的断言还是有点模糊;在老师给出的任务中我也相应实践过程中学习了到了异常处理的好处,对我后期的学习会帮助很大。

猜你喜欢

转载自www.cnblogs.com/JerryLau-213/p/11779106.html