杨玲 201771010133《面向对象程序设计(java)》第九周学习总结

《面向对象程序设计(java)》第九周学习总结

第一部分:理论知识

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

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

程序中出现的常见的错误和问题有:用户输入错误;设备错误;物理限制;代码错误。

Java把程序运行时可能遇到的错误分为两类:非致命异常:通过某种修正后程序还能继续执行。这类错误叫作异常。如:文件不存在、无效的数组下标、空引用、网络断开、打印机脱机、磁盘满等。 Java中提供了一种独特的处理异常的机制,通过异常来处理程序设计中出现的错误。致命异常:程序遇到了非常严重的不正常状态,不能简单恢复执行,是致命性错误。如:内存耗尽、系统内部错误等。这种错误程序本身无法解决。

Java中所有的异常类都直接或间接地继承于Throwable类。除内置异常类外,程序员可自定义异常类。

Java中的异常类可分为两大类: Error :Error类层次结构描述了Java 运行时系统的内部错误和资源耗尽错误。应用程序不应该捕获这类异常,也不会抛出这种异常 。 Exception类: Exception层次结构又分解为两个分支:一个分支派生于 RuntimeException;另一个分支包含其他异常。

RuntimeException为运行时异常类,一般是程序错误产生。派生于RuntimeException的异常包含下面几种情况:错误的类型转换;数组访问越界;访问空指针。

Java将派生于Error类或RuntimeException类的所有异常称为未检查异常,编译器允许不对它们做出异常处理。 注意:“如果出现RuntimeException异常,就一定是程序员的问题!!!”

非运行时异常,程序本身没有问题,但由于某种情况的变化,程序不能正常运行,导致异常出现。除了运行时异常之外的其它继承自Exception类的异常类包括:试图在文件尾部后面读取数据;试图打开一个错误格式的URL。 编译器要求程序必须对这类异常进行处理 (checked),称为已检查异常。

RuntimeException运行时异常类:ArithmeticException: 算术异常类;ArrayStoreException: 数组存储异常类;ClassCastException: 类型强制转换异常类;IndexOutOfBoundsException: 下标越界异常类;NullPointerException: 空指针异常类;SecurityException: 违背安全原则异常类。

IOException:输入输出异常类:IOException:申请I/O操作没有正常完成。EOFException:在输入操作正常结束前遇见了文件结束符。FileNotFountException:在文件系统中,没有找到由文件名字符串指定的文件。

声明抛出异常:如果一个方法可能会生成一些异常,但是该方法并不确切知道如何对这些异常事件进行处理,此时,这个方法就需声明抛出这些异常。“一个方法不仅需要告诉编译器将要返回什么值,还要告诉编译器可能发生什么异常。”

声明抛出异常在方法声明中用throws子句中来指明。例如:public FileInputStream(String name ) throws FileNotFoundException

throws子句可以同时指明多个异常,说明该方法将不对这些异常进行处理,而是声明抛出它们。public static void main(String args[]) throws IOException,IndexOutOfBoundsException

以下4种情况需要方法用throws子句声明抛出异常:1、方法调用了一个抛出已检查异常的方法。2、程序运行过程中可能会发生错误,并且利用throw语句抛出一个已检查异常对象。 3、程序出现错误。例如,a[-1] = 0/4、Java虚拟机和运行时库出现的内部异常。

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

当Java应用程序出现错误时,会根据错误类型产生一个异常对象,这个对象包含了异常的类型和错误出现时程序所处的状态信息。把异常对象递交给Java编译器的过程称为抛出。抛出异常要生成异常对象,异常对象可由某些类的实例生成,也可以由JVM生成。抛出异常对象通过throw语句来实现。

如何抛出异常:首先决定抛出异常类型。例如:当从一个长为 1024的文件中读取数据时,但读到733时遇到了文件结束标记,此时应抛出一个异常,EOFException比较合适。代码为:throw new EOFException(); 或者: EOFException e= new EOFException(); throw e;

对于已存在的异常类,抛出该类的异常对象非常容易,步骤是:找到一个合适的异常类;创建这个类的一个对象;将该对象抛出。一个方法抛出了异常后,它就不能返回调用者了。

创建异常类:自定义异常类:定义一个派生于Exception的直接或间接子类。如一个派生于IOException的类。自定义的异常类应该包括两个构造器:默认构造器;带有详细描述信息的构造器(超类Throwable的toString方法会打印出这些详细信息,有利于代码调试)

程序运行期间,异常发生时,Java运行系统从异常生成的代码块开始,寻找相应的异常处理代码,并将异常交给该方法处理,这一过程叫作捕获。某个异常发生时,若程序没有在任何地方进行该异常的捕获,则程序就会终止执行,并在控制台上输出异常信息。若要捕获一个异常,需要在程序中设置一个try/catch/ finally块: try语句括住可能抛出异常的代码段。catch语句指明要捕获的异常及相应的处理代码。finally语句指明必须执行的程序块。

try子句:捕获异常的第一步是用try{…}子句选定捕获异常的代码范围,由try所限定的代码块中的语句在执行过程中可能会自动生成异常对象并抛出。对于异常处理,可以捕获,也可以只声明抛出不作任何处理。

catch子句:catch块是对异常对象进行处理的代码;每个try代码块可以伴随一个或多个catch语句,用于处理 try代码块中所生成的各类异常事件;catch语句只需要一个形式参数指明它所能捕获的异常类对象,这个异常类必须是Throwable的子类,运行时系统通过参数值把被抛出的异常对象传递给catch块;catch块可以通过异常对象调用类Throwable所提供的方法。getMessage()用来得到有关异常事件的信息;printStackTrace()用来跟踪异常事件发生时执行堆栈的内容。

可以在一个try块中捕获多个异常类型,每个异常类型需要个单独的catch子句。

try{ 抛出异常代码}

catch(ExceptionType1 e1){ 抛出exceptionType1时要执行的代码 }

catch(ExceptionType2 e2){ 抛出exceptionType2时要执行的代码 }

 catch(ExceptionType3 e3){ 抛出exceptionType3时要执行的代码 }

catch语句的顺序:捕获异常的顺序和不同catch语句的顺序有关,当捕获到一个异常时。剩下的catch语句就不再进行匹配。因此在安排catch语句的顺序时,首先应该捕获最特殊的异常,然后在逐渐一般化,也就是一般先安排子类,再安排父类。

再次抛出异常与异常链catch子句中也可以抛出一个异常,这样做的目的是改变异常的类型。

finally子句:捕获异常的最后一步是通过finally语句为异常处理提供一个统一的出口,使得控制流程在转到程序其它部分以前,能够对程序的状态做统一的管理。不论在 try代码块中是否发生了异常事件,finally块中的语句都会被执行。

Java异常捕获处理代码的一般形式是: try {//括号内为被监视程序块 }

catch(异常类1 e1){//括号内为处理异常类1的程序块}

catch(异常类2 e2){//括号内为处理异常类2的程序块}

 … …

catch (异常类n en){//括号内为处理异常类n的程序块}

finally {//括号内为必须要执行的程序块 }

程序编码时异常处理的两种方式:积极处理方式:确切知道如何处理的异常应该捕获;消极处理方式:不知道如何去处理的异常声明抛出。

异常处理的原则:(1) 异常处理不能代替简单的条件检测,只在异常情况下使用异常机制。(2) 程序代码不要过分细化异常,尽量将有可能产生异常的语句放在一个try语句块中。(3) 抛出的异常类型尽可能明确。(4) 不要压制异常,对于很少发生的异常,应该将其关闭。(5) 早抛出,晚捕获,尽量让高层次的方法通告用户发生了错误。

 第二部分:实验部分

1.实验名称:实验九 异常、断言与日志

2.  实验目的:

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

(2) 了解断言的用法;

(3) 了解日志的用途;

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

3. 实验步骤与内容:

 实验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 {
 2     public static void main(String args[]) {
 3         int a = 0;
 4         if(a==0) {
 5             
 6             System.out.println("除数为0");
 7         }
 8         else
 9         System.out.println(5 / a);
10     }
11 }
 1 //异常示例2
 2 
 3 import java.io.*;
 4 
 5  
 6 
 7 public class ExceptionDemo2 {
 8 
 9 public static void main(String args[]) throws IOException 
10 
11      {
12 
13           FileInputStream fis=new FileInputStream("身份证号.txt");//JVM自动生成异常对象
14 
15           int b;
16 
17           while((b=fis.read())!=-1)
18 
19           {
20 
21               System.out.print(b);
22 
23           }
24 
25           fis.close();
26         System.out.print("身份证号.txt");
27 
28       }
29      
30 }

 程序运行结果如下:

杨玲 201771010133《面向对象程序设计(java)》第九周学习总结

 杨玲 201771010133《面向对象程序设计(java)》第九周学习总结

实验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.01 2004-05-10
 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 + "):");
20       Throwable t = new Throwable();
21       StackTraceElement[] frames = t.getStackTrace();//使用getStackTrace方法,它会得到StackTraceElement对象的一个数组,StackTraceElement类含有能够获得文件名和当前执行的代码行号的方法,同时,还含有能够获得类名和方法名的方法
22 for (StackTraceElement f : frames) 
23 System.out.println(f);
24 int r;
25 if (n <= 1) r = 1;
26 else r = n * factorial(n - 1);
27 System.out.println("return " + r);
28 return r;
29 }
30
31 public static void main(String[] args)
32 {
33 Scanner in = new Scanner(System.in);
34 System.out.print("Enter n: ");
35 int n = in.nextInt();
36 factorial(n);
37 }
38 }

程序运行结果如下:

杨玲 201771010133《面向对象程序设计(java)》第九周学习总结

测试程序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 ExceptionTest1 {

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

     {

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

     }

}

 1 //积极处理方式  
 2 
 3 import java.io.*;
 4 import java.io.BufferedReader;
 5 import java.io.FileReader;
 6 
 7  
 8 
 9 class ExceptionTest {
10 
11 public static void main (String args[])
12 
13    {
14     
15        File fis=new File("身份证号.txt");
16 
17        try{
18 
19            FileReader fr = new FileReader(fis);
20            BufferedReader br = new BufferedReader(fr);
21            try {
22                String s, s2 = new String();
23                while ((s = br.readLine()) != null) {
24                    s2 += s + "
 ";
25                }
26                br.close();
27                System.out.println(s2);
28            } catch (IOException e) {
29                // TODO Auto-generated catch block
30                e.printStackTrace();
31            }
32        } catch (FileNotFoundException e) {
33            // TODO Auto-generated catch block
34            e.printStackTrace();
35        }
36 
37     }
38   }
 1 //消极处理方式
 2 
 3 import java.io.*;
 4 class ExceptionDemo1 {
 5     public static void main (String args[]) throws  IOException
 6        {
 7         File fis=new File("身份证号.txt");
 8         FileReader fr = new FileReader(fis);
 9         BufferedReader br = new BufferedReader(fr);
10         String s, s2 = new String();
11 
12             while ((s = br.readLine()) != null) {
13                 s2 += s + "
 ";
14             }
15             br.close();
16             System.out.println(s2);
17        }
18 }

杨玲 201771010133《面向对象程序设计(java)》第九周学习总结

 实验3: 编程练习

练习1

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

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

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

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

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

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

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

  1 import java.io.BufferedReader;
  2 import java.io.File;
  3 import java.io.FileInputStream;
  4 import java.io.FileNotFoundException;
  5 import java.io.IOException;
  6 import java.io.InputStreamReader;
  7 import java.util.ArrayList;
  8 import java.util.Arrays;
  9 import java.util.Collections;
 10 import java.util.Scanner;
 11 
 12 public class Main{
 13     private static ArrayList<Person> Personlist;
 14     public static void main(String[] args) {
 15         Personlist = new ArrayList<>();
 16         Scanner scanner = new Scanner(System.in);
 17         File file = new File("D:\身份证号.txt");
 18         try {
 19             FileInputStream fis = new FileInputStream(file);
 20             BufferedReader in = new BufferedReader(new InputStreamReader(fis));
 21             String temp = null;
 22             while ((temp = in.readLine()) != null) {
 23                 
 24                 Scanner linescanner = new Scanner(temp);
 25                 
 26                 linescanner.useDelimiter(" ");    
 27                 String name = linescanner.next();
 28                 String ID = linescanner.next();
 29                 String sex = linescanner.next();
 30                 String age = linescanner.next();
 31                 String place =linescanner.nextLine();
 32                 Person Person = new Person();
 33                 Person.setname(name);
 34                 Person.setID(ID);
 35                 Person.setsex(sex);
 36                 int a = Integer.parseInt(age);
 37                 Person.setage(a);
 38                 Person.setbirthplace(place);
 39                 Personlist.add(Person);
 40 
 41             }
 42         } catch (FileNotFoundException e) {
 43             System.out.println("查找不到信息");
 44             e.printStackTrace();
 45         } catch (IOException e) {
 46             System.out.println("信息读取有误");
 47             e.printStackTrace();
 48         }
 49         boolean isTrue = true;
 50         while (isTrue) {
 51             System.out.println("————————————————————————————————————————");
 52             System.out.println("1:按姓名字典序输出人员信息");
 53             System.out.println("2:查询最大年龄与最小年龄人员信息");
 54             System.out.println("3:按省份找同乡");
 55             System.out.println("4:输入你的年龄,查询年龄与你最近人的信息");
 56             System.out.println("5:exit");
 57             int nextInt = scanner.nextInt();
 58             switch (nextInt) {
 59             case 1:
 60                 Collections.sort(Personlist);
 61                 System.out.println(Personlist.toString());
 62                 break;
 63             case 2:
 64                 
 65                 int max=0,min=100;int j,k1 = 0,k2=0;
 66                 for(int i=1;i<Personlist.size();i++)
 67                 {
 68                     j=Personlist.get(i).getage();
 69                    if(j>max)
 70                    {
 71                        max=j; 
 72                        k1=i;
 73                    }
 74                    if(j<min)
 75                    {
 76                        min=j; 
 77                        k2=i;
 78                    }
 79 
 80                 }  
 81                 System.out.println("年龄最大:"+Personlist.get(k1));
 82                 System.out.println("年龄最小:"+Personlist.get(k2));
 83                 break;
 84             case 3:
 85                 System.out.println("place?");
 86                 String find = scanner.next();        
 87                 String place=find.substring(0,3);
 88                 String place2=find.substring(0,3);
 89                 for (int i = 0; i <Personlist.size(); i++) 
 90                 {
 91                     if(Personlist.get(i).getbirthplace().substring(1,4).equals(place)) 
 92                         System.out.println("maybe is      "+Personlist.get(i));
 93 
 94                 } 
 95 
 96                 break;
 97             case 4:
 98                 System.out.println("年龄:");
 99                 int yourage = scanner.nextInt();
100                 int near=agenear(yourage);
101                 int d_value=yourage-Personlist.get(near).getage();
102                 System.out.println(""+Personlist.get(near));
103            /*     for (int i = 0; i < Personlist.size(); i++)
104                 {
105                     int p=Personlist.get(i).getage()-yourage;
106                     if(p<0) p=-p;
107                     if(p==d_value) System.out.println(Personlist.get(i));
108                 }   */
109                 break;
110             case 5:
111            isTrue = false;
112            System.out.println("退出程序!");
113                 break;
114             default:
115                 System.out.println("输入有误");
116             }
117         }
118     }
119     public static int agenear(int age) {
120      
121        int j=0,min=53,d_value=0,k=0;
122         for (int i = 0; i < Personlist.size(); i++)
123         {
124             d_value=Personlist.get(i).getage()-age;
125             if(d_value<0) d_value=-d_value; 
126             if (d_value<min) 
127             {
128                min=d_value;
129                k=i;
130             }
131 
132          }    return k;
133         
134      }
135 
136  
137 }
 1 public class Person implements Comparable<Person> {
 2 private String name;
 3 private String ID;
 4 private int age;
 5 private String sex;
 6 private String birthplace;
 7 
 8 public String getname() {
 9 return name;
10 }
11 public void setname(String name) {
12 this.name = name;
13 }
14 public String getID() {
15 return ID;
16 }
17 public void setID(String ID) {
18 this.ID= ID;
19 }
20 public int getage() {
21 
22 return age;
23 }
24 public void setage(int age) {
25     // int a = Integer.parseInt(age);
26 this.age= age;
27 }
28 public String getsex() {
29 return sex;
30 }
31 public void setsex(String sex) {
32 this.sex= sex;
33 }
34 public String getbirthplace() {
35 return birthplace;
36 }
37 public void setbirthplace(String birthplace) {
38 this.birthplace= birthplace;
39 }
40 
41 public int compareTo(Person o) {
42    return this.name.compareTo(o.getname());
43 
44 }
45 
46 public String toString() {
47     return  name+"	"+sex+"	"+age+"	"+ID+"	"+birthplace+"
";
48 
49 }
50 
51 
52 
53 }

运行结果如下:

杨玲 201771010133《面向对象程序设计(java)》第九周学习总结

杨玲 201771010133《面向对象程序设计(java)》第九周学习总结

杨玲 201771010133《面向对象程序设计(java)》第九周学习总结

练习2

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

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

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

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

 1 import java.io.FileNotFoundException;
 2 import java.io.PrintWriter;
 3 import java.util.Scanner;
 4 
 5 /*
 6  * 该程序用来随机生成0到100以内的加减乘除题
 7  */
 8 public class Demo {
 9     public static  void main(String[] args) {
10         // 用户的答案要从键盘输入,因此需要一个键盘输入流
11         Scanner in = new Scanner(System.in);
12         Counter counter=new Counter();
13         PrintWriter out = null;
14         try {
15             out = new PrintWriter("text.txt");
16         } catch (FileNotFoundException e) {
17             // TODO Auto-generated catch block
18             e.printStackTrace();
19         }
20         // 定义一个变量用来统计得分
21         int sum = 0;
22         int k=0;
23         // 通过循环生成10道题
24         for (int i = 0; i < 10; i++) {
25 
26             // 随机生成两个100以内的随机数作加减乘除
27             int a = (int) Math.round(Math.random() * 100);
28             int b = (int) Math.round(Math.random() * 100);
29             int d = (int) Math.round(Math.random() * 3);
30             
31             switch (d){
32             
33             case 0: 
34               System.out.println(a + "/" + b + "=");
35               //int c = in.nextInt();
36               //out.println(a + "/" + b + "="+c);
37             break;
38             case 1:
39               System.out.println(a + "*" + b + "=");
40               //int c1 = in.nextInt();
41               //out.println(a + "*" + b + "="+c1);
42             break;
43             case 2:
44               System.out.println(a + "+" + b + "=");
45               //int c2 = in.nextInt();
46               //out.println(a + "+" + b + "="+c2);
47             break;
48             case 3:
49             System.out.println(a + "-" + b + "=");
50             //int c3 = in.nextInt();
51             //out.println(a + "-" + b + "="+c3);
52             break;
53             }        
54 
55             // 定义一个整数用来接收用户输入的答案
56             double c = in.nextDouble();
57             
58             // 判断用户输入的答案是否正确,正确给10分,错误不给分
59             if (c == a / b | c == a * b | c == a + b | c == a - b) {
60                 sum += 10;
61                 System.out.println("恭喜答案正确");
62             }
63             else {
64                 System.out.println("抱歉,答案错误");
65             
66             }
67             out.println(a + "/" + b + "="+c );
68             out.println(a + "*" + b + "="+c);
69             out.println(a + "+" + b + "="+c);
70             out.println(a + "-" + b + "="+c);
71         
72         }
73         //输出用户的成绩
74         System.out.println("你的得分为"+sum);
75         
76         out.println("成绩:"+sum);
77         out.close();
78     }
79     }

杨玲 201771010133《面向对象程序设计(java)》第九周学习总结

 杨玲 201771010133《面向对象程序设计(java)》第九周学习总结

实验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,结合程序运行结果理解程序;

 运行结果如下:

杨玲 201771010133《面向对象程序设计(java)》第九周学习总结

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

运行结果如下:

杨玲 201771010133《面向对象程序设计(java)》第九周学习总结

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

 1 //断言程序示例
 2 
 3 public class AssertDemo {
 4 
 5     public static void main(String[] args) {        
 6 
 7         //test1(-5);
 8 
 9         test2(-3);
10 
11     }
12 
13     
14 
15     private static void test1(int a){
16 
17         assert a > 0;
18 
19         System.out.println(a);
20 
21     }
22 
23     private static void test2(int a){
24 
25        assert a > 0 : "something goes wrong here, a cannot be less than 0";
26 
27         System.out.println(a);
28 
29     }
30 
31 }

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

 杨玲 201771010133《面向对象程序设计(java)》第九周学习总结

 杨玲 201771010133《面向对象程序设计(java)》第九周学习总结

实验程序3:

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

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

4. 实验总结:

 通过本次实验我掌握了java异常处理的技术;了解了断言的用法和日志的用途;掌握程序了基础调试的技巧。