• 201771010126 王燕《面向对象程序设计(Java)》第九周学习总结


    实验九 异常、断言与日志

    实验时间 2018-10-25

    1、实验目的与要求

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

    异常积极处理方法:使用try子句捕获异常

    异常小计处理方法:抛出throw异常类

    (2) 了解断言的用法;

    断言:是一种错误处理机制,是在程序的开发和测试阶段使用的工具。
    断言(assert)是JDK1.4中引入的一个新的关键字,语法如下:
    assert  条件   或者assert  条件:表达式
      这两个形式都会对“条件”进行判断, “条件”是一个布尔表达式。如果判断结果为假(false)则抛出AssertionError。在第二种形式中,“表达式”会传进AssertionError的构造函数中并转成一个消息字符串。
    “表达式”部分的唯一目的就是生成一个消息字符串。 AssertionError对象并不存储表达式的值,因此你不可能在以后获取它。

    断言仅仅应该在测试阶段用来定位程序内部错误。
    可以将断言语句作为方法的前置条件或后置条件来添加,也可以将其置于任何方法内,或放在if…else块和switch块中。assert 关键字的唯一限制在于它必须位于可执行块中。  
    对一个方法调用是否使用断言,应先看看该方法的文档。如果文档指明在某种情况下会抛出异常,那么对这种情况不需使用断言;如果文档指明一个限制条件,但没有说明违反该条件会抛出异常,此时就可以使用断言。

    (3) 了解日志的用途;

    记录日志API就是为了帮助程序员观察程序运行的操作过程而设计的。
    记录日志API的主要优点:
    可以很容易地取消全部日志记录。
    可以和简单地禁止日志记录的输出。
    日志记录可以被定向到不同的处理器。
    日志记录器和处理器都可以对日志进行过滤。
    日志记录可以采用不同的方式格式化。
    应用程序可以使用多个日志记录器。
    在默认情况下,日志系统的配置由配置文件控制。

    基本日志,高级日志,修改日志管理器配置,本地化,处理器,过滤器, 格式化器,日志记录说明

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

    应用打印语句或记录任意变量的值

    在每个类中放置一个单独的main方法

    使用printStackTrace方法跟踪

    定义用于调试的特殊类

    使用断言调试程序

    使用日志代理(logging proxy)

    应用Java虚拟机的功能

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

          }

    }

     

     

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

    测试程序1:

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

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

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

     1 import java.util.*;
     2 
     3 /**
     4  * A program that displays a trace feature of a recursive method call.
     5  * @version 1.01 2004-05-10
     6  * @author Cay Horstmann
     7  */
     8 public class StackTraceTest
     9 {
    10    /**
    11     * Computes the factorial of a number
    12     * @param n a non-negative integer
    13     * @return n! = 1 * 2 * . . . * n
    14     */
    15    public static int factorial(int n)
    16    {
    17       System.out.println("factorial(" + n + "):");
    18       Throwable t = new Throwable();
    19       StackTraceElement[] frames = t.getStackTrace();
    20       for (StackTraceElement f : frames)
    21          System.out.println(f);
    22       int r;
    23       if (n <= 1) r = 1;
    24       else r = n * factorial(n - 1);
    25       System.out.println("return " + r);
    26       return r;
    27    }
    28 
    29    public static void main(String[] args)
    30    {
    31       Scanner in = new Scanner(System.in);
    32       System.out.print("Enter n: ");
    33       int n = in.nextInt();
    34       factorial(n);
    35    }
    36 }

     

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

         }

    }

     1 //积极处理方式  
     2 import java.io.*;
     3 import java.io.BufferedReader;
     4 import java.io.FileReader;
     5 
     6 class ExceptionTest {
     7     public static void main (String args[])
     8  {
     9         File fis=new File("G:\JAVA\实验\studentfile.txt");
    10      try{
    11          
    12 
    13          FileReader fr = new FileReader(fis);
    14          BufferedReader br = new BufferedReader(fr);
    15          try {
    16              String s, s2 = new String();
    17              while ((s = br.readLine()) != null) {
    18                  s2 += s + "
     ";
    19              }
    20              br.close();
    21              System.out.println(s2);
    22          } catch (IOException e) {
    23              e.printStackTrace();
    24          }
    25      } catch (FileNotFoundException e) {
    26          e.printStackTrace();
    27      }
    28 
    29   }
    30 }

       

     1 //消极处理方式
     2 import java.io.*;
     3 class ExceptionTest1 {
     4     public static void main (String args[]) throws  IOException
     5        {
     6         File fis=new File("G:\JAVA\实验\studentfile.txt");
     7         FileReader fr = new FileReader(fis);
     8         BufferedReader br = new BufferedReader(fr);
     9         String s, s2 = new String();
    10 
    11             while ((s = br.readLine()) != null) {
    12                 s2 += s + "
     ";
    13             }
    14             br.close();
    15             System.out.println(s2);
    16        }
    17 }

     

    实验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 Check{
     13     private static ArrayList<Student> studentlist;
     14     public static void main(String[] args) {
     15         studentlist = new ArrayList<>();
     16         Scanner scanner = new Scanner(System.in);
     17         File file = new File("C:\下载\身份证号.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 number = linescanner.next();
     29                 String sex = linescanner.next();
     30                 String age = linescanner.next();
     31                 String province =linescanner.nextLine();
     32                 Student student = new Student();
     33                 student.setName(name);
     34                 student.setnumber(number);
     35                 student.setsex(sex);
     36                 int a = Integer.parseInt(age);
     37                 student.setage(a);
     38                 student.setprovince(province);
     39                 studentlist.add(student);
     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.退出");
     57             String m = scanner.next();
     58             switch (m) {
     59             case "1":
     60                 Collections.sort(studentlist);              
     61                 System.out.println(studentlist.toString());
     62                 break;
     63             case "2":
     64                  int max=0,min=100;
     65                  int j,k1 = 0,k2=0;
     66                  for(int i=1;i<studentlist.size();i++)
     67                  {
     68                      j=studentlist.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("年龄最大:"+studentlist.get(k1));
     82                  System.out.println("年龄最小:"+studentlist.get(k2));
     83                 break;
     84             case "3":
     85                  System.out.println("输入省份");
     86                  String find = scanner.next();        
     87                  String place=find.substring(0,3);
     88                  for (int i = 0; i <studentlist.size(); i++) 
     89                  {
     90                      if(studentlist.get(i).getprovince().substring(1,4).equals(place)) 
     91                          System.out.println("老乡"+studentlist.get(i));
     92                  }             
     93                  break;
     94                  
     95             case "4":
     96                 System.out.println("年龄:");
     97                 int yourage = scanner.nextInt();
     98                 int near=agenear(yourage);
     99                 int value=yourage-studentlist.get(near).getage();
    100                 System.out.println(""+studentlist.get(near));
    101                 break;
    102             case "5":
    103                 isTrue = false;
    104                 System.out.println("退出程序!");
    105                 break;
    106                 default:
    107                 System.out.println("输入有误");
    108 
    109             }
    110         }
    111     }
    112         public static int agenear(int age) {      
    113         int j=0,min=53,value=0,k=0;
    114          for (int i = 0; i < studentlist.size(); i++)
    115          {
    116              value=studentlist.get(i).getage()-age;
    117              if(value<0) value=-value; 
    118              if (value<min) 
    119              {
    120                 min=value;
    121                 k=i;
    122              } 
    123           }    
    124          return k;         
    125       }
    126 
    127 }
     1 public class Student implements Comparable<Student> {
     2 
     3     private String name;
     4     private String number ;
     5     private String sex ;
     6     private int age;
     7     private String province;
     8    
     9     public String getName() {
    10         return name;
    11     }
    12     public void setName(String name) {
    13         this.name = name;
    14     }
    15     public String getnumber() {
    16         return number;
    17     }
    18     public void setnumber(String number) {
    19         this.number = number;
    20     }
    21     public String getsex() {
    22         return sex ;
    23     }
    24     public void setsex(String sex ) {
    25         this.sex =sex ;
    26     }
    27     public int getage() {
    28 
    29         return age;
    30         }
    31         public void setage(int age) {
    32             // int a = Integer.parseInt(age);
    33         this.age= age;
    34         }
    35 
    36     public String getprovince() {
    37         return province;
    38     }
    39     public void setprovince(String province) {
    40         this.province=province ;
    41     }
    42 
    43     public int compareTo(Student o) {
    44        return this.name.compareTo(o.getName());
    45     }
    46 
    47     public String toString() {
    48         return  name+"	"+sex+"	"+age+"	"+number+"	"+province+"
    ";
    49     }    
    50 }

     

     

     注:以下实验课后完成

    练习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 public class Caculator {
      5     public static void main(String[] args) {
      6         Scanner in = new Scanner(System.in);
      7         Caculator1 computing=new Caculator1();
      8         PrintWriter output = null;
      9         try {
     10             output = new PrintWriter("Caculator.txt");
     11         } catch (Exception e) {
     12         }
     13         int sum = 0;
     14 
     15         for (int i = 1; i < 11; i++) {
     16             int a = (int) Math.round(Math.random() * 100);
     17             int b = (int) Math.round(Math.random() * 100);
     18             int s = (int) Math.round(Math.random() * 3);
     19         switch(s)
     20         {
     21            case 1:
     22                System.out.println(i+": "+a+"/"+b+"=");
     23                while(b==0){  
     24                    b = (int) Math.round(Math.random() * 100); 
     25                    }
     26                double c = in.nextDouble();
     27                output.println(a+"/"+b+"="+c);
     28                if (c == (double)computing.division(a, b)) {
     29                    sum += 10;
     30                    System.out.println("T");
     31                }
     32                else {
     33                    System.out.println("F");
     34                }
     35             
     36                break;
     37             
     38            case 2:
     39                System.out.println(i+": "+a+"*"+b+"=");
     40                int c1 = in.nextInt();
     41                output.println(a+"*"+b+"="+c1);
     42                if (c1 == computing.multiplication(a, b)) {
     43                    sum += 10;
     44                    System.out.println("T");
     45                }
     46                else {
     47                    System.out.println("F");
     48                }
     49                break;
     50            case 3:
     51                System.out.println(i+": "+a+"+"+b+"=");
     52                int c2 = in.nextInt();
     53                output.println(a+"+"+b+"="+c2);
     54                if (c2 == computing.addition(a, b)) {
     55                    sum += 10;
     56                    System.out.println("T");
     57                }
     58                else {
     59                    System.out.println("F");
     60                }
     61                
     62                break ;
     63            case 4:
     64                System.out.println(i+": "+a+"-"+b+"=");
     65                int c3 = in.nextInt();
     66                output.println(a+"-"+b+"="+c3);
     67                if (c3 == computing.subtraction(a, b)) {
     68                    sum += 10;
     69                    System.out.println("T");
     70                }
     71                else {
     72                    System.out.println("F");
     73                }
     74                break ;
     75 
     76                } 
     77     
     78           }
     79         System.out.println("scores:"+sum);
     80         output.println("scores:"+sum);
     81         output.close();
     82          
     83     }
     84 }
     85 class Caculator1
     86 {
     87        private int a;
     88        private int b;
     89         public int  addition(int a,int b)
     90         {
     91             return a+b;
     92         }
     93         public int  subtraction(int a,int b)
     94         {
     95             if((a-b)<0)
     96                 return 0;
     97             else
     98             return a-b;
     99         }
    100         public int   multiplication(int a,int b)
    101         {
    102             return a*b;
    103         }
    104         public int   division(int a,int b)
    105         {
    106             if(b!=0)
    107             return a/b;    
    108             else
    109         return 0;
    110         }
    111 
    112         
    113 }

     

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

    实验程序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             Handler 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                Handler windowHandler = new WindowHandler();
     38                windowHandler.setLevel(Level.ALL);
     39                Logger.getLogger("com.horstmann.corejava").addHandler(windowHandler);
     40 
     41                JFrame 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       JMenuBar menuBar = new JMenuBar();
     69       setJMenuBar(menuBar);
     70 
     71       JMenu menu = new JMenu("File");
     72       menuBar.add(menu);
     73 
     74       JMenuItem openItem = new JMenuItem("Open");
     75       menu.add(openItem);
     76       openItem.addActionListener(new FileOpenListener());
     77 
     78       JMenuItem 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          JFileChooser 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       final JTextArea 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 }

     

    实验程序3:

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

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

      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             Handler 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                Handler windowHandler = new WindowHandler();
     38                windowHandler.setLevel(Level.ALL);
     39                Logger.getLogger("com.horstmann.corejava").addHandler(windowHandler);
     40 
     41                JFrame 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       JMenuBar menuBar = new JMenuBar();
     69       setJMenuBar(menuBar);
     70 
     71       JMenu menu = new JMenu("File");
     72       menuBar.add(menu);
     73 
     74       JMenuItem openItem = new JMenuItem("Open");
     75       menu.add(openItem);
     76       openItem.addActionListener(new FileOpenListener());
     77 
     78       JMenuItem 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          JFileChooser 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       final JTextArea 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 }

     实验总结

    通过这周的学习,对程序中编译时出现的错误和运行时出现的错误有了进一步的认识以及理解,对程序中出现的异常的种类以及出现错误时如何抛出错误,捕获错误,

    以及使用try和catch进行异常处理有了一定的掌握

    用throw子句声明异常:
    a.调用一个抛出受查异常的方法。
    b.程序运行过程中发现错误,并且利用throw语句抛出一个受查异常。
    c.程序出现错误。
    d.Java虚拟机和运行时出现的内部异常。
    e.一个方法必须声明所有可能抛出的受查异常,而未检查异常要么不可控制(Error),要么应该避免发生(RuntimeException)。如果方法没有声明所有可能发生的受查异常,编译器就会给出一个错误消息。

  • 相关阅读:
    搭建前端监控系统(备选)Js截图上报篇
    搭建前端监控系统(三)静态资源加载监控篇
    搭建前端监控系统(一)阿里云服务器搭建篇
    springboot+缓存
    springboot集成springDataJpa
    从零开始搭建SpringBoot项目
    Java1.8的HashMap源码解析
    SpringMvc流程分析,简单源码分析
    Java定时任务
    Java性能调优
  • 原文地址:https://www.cnblogs.com/wy201771010126/p/9863268.html
Copyright © 2020-2023  润新知