第一部分 理论部分
第二部分 实验部分
1、实验目的与要求
(1) 掌握java异常处理技术;
Java的异常处理机制可以控制程序从错误产生的 位置转移到能够进行错误处理的位置。程序中出现的常见的错误和问题有:用户输入错误 ;设备错误 ;物理限制 ;代码错误。通常分为非致命异常和致命异常两类。非致命异常:通过某种修正后程序还能继续执行。 这类错误叫作异常。如:文件不存在、无效的数组 下标、空引用、网络断开等。 Java中提供了一种独特的处理异常的机制,通过异常来处理程序设计中出现的错误。另一种是致命异常:程序遇到了非常严重的不正常状态,不 能简单恢复执行,是致命性错误。如:内存耗尽、 系统内部错误等。这种错误程序本身无法解决。除此之外Java中的异常类可分为两大类:一类是Error Error类层次结构描述了Java运行时系统的内部错误 和资源耗尽错误。应用程序不应该捕获这类异常,也 不会抛出这种异常。另一类是Exception Exception类:重点掌握的异常类。Exception层次结 构又分解为两个分支:一个分支派生于 RuntimeException;另一个分支包含其他异常
(2) 了解断言的用法;
断言:是一种错误处理机制,是在程序的开发和测试阶段使用的工具。
断言(assert)是JDK1.4中引入的一个新的关键字,语法如下:
assert 条件 或者assert 条件:表达式
这两个形式都会对“条件”进行判断, “条件”是一个布尔表达式。如果判断结果为假(false)则抛出AssertionError。在第二种形式中,“表达式”会传进AssertionError的构造函数中并转成一个消息字符串。
“表达式”部分的唯一目的就是生成一个消息字符串。 AssertionError对象并不存储表达式的值,因此你不可能在以后获取它。
(3) 了解日志的用途;
记录日志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 package vxdfuey; 2 //积极处理方式 3 import java.io.*; 4 import java.io.BufferedReader; 5 import java.io.FileReader; 6 7 class ExceptionTest { 8 public static void main (String args[]) 9 { 10 File fis=new File("C:\Users\admin\Documents\Tencent Files\2247955978\FileRecv\身份证号.txt"); 11 try{ 12 13 14 FileReader fr = new FileReader(fis); 15 BufferedReader br = new BufferedReader(fr); 16 try { 17 String s, s2 = new String(); 18 while ((s = br.readLine()) != null) { 19 s2 += s + " "; 20 } 21 br.close(); 22 System.out.println(s2); 23 } catch (IOException e) { 24 e.printStackTrace(); 25 } 26 } catch (FileNotFoundException e) { 27 e.printStackTrace(); 28 } 29 30 } 31 }
1 package vxdfuey; 2 //消极处理方式 3 import java.io.*; 4 class ExceptionTest1 { 5 public static void main (String args[]) throws IOException 6 { 7 File fis=new File("C:\\Users\\admin\\Documents\\Tencent Files\\2247955978\\FileRecv\\身份证号.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 }
实验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 M{ 13 private static ArrayList<Test> studentlist; 14 public static void main(String[] args) { 15 studentlist = 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 number = linescanner.next(); 29 String sex = linescanner.next(); 30 String age = linescanner.next(); 31 String province =linescanner.nextLine(); 32 Test student = new Test(); 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 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("province?"); 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("province"+studentlist.get(i)); 92 } 93 break; 94 95 case "4": 96 System.out.println("年龄:"); 97 int yourage = scanner.nextInt(); 98 int near=agematched(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 agematched(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 }
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.Scanner; public class M{ private static ArrayList<Test> 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(); Test student = new Test(); 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) { System.out.println("学生信息文件找不到"); e.printStackTrace(); } catch (IOException e) { System.out.println("学生信息文件读取错误"); e.printStackTrace(); } boolean isTrue = true; while (isTrue) { System.out.println("1:字典排序"); System.out.println("2:输出年龄最大和年龄最小的人"); System.out.println("3:寻找老乡"); System.out.println("4:寻找年龄相近的人"); System.out.println("5:退出"); String m = scanner.next(); switch (m) { 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("province?"); 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("province"+studentlist.get(i)); } break; case "4": System.out.println("年龄:"); int yourage = scanner.nextInt(); int near=agematched(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 agematched(int age) { int j=0,min=53,value=0,k=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; k=i; } } return k; } } M
练习2:
l 编写一个计算器类,可以完成加、减、乘、除的操作;
l 利用计算机类,设计一个小学生100以内数的四则运算练习程序,由计算机随机产生10道加减乘除练习题,学生输入答案,由程序检查答案是否正确,每道题正确计10分,错误不计分,10道题测试结束后给出测试总分;
l 将程序中测试练习题及学生答题结果输出到文件,文件名为test.txt;
l 在以上程序适当位置加入异常捕获代码。
1 package vxdfuey; 2 3 import java.io.FileNotFoundException; 4 import java.io.PrintWriter; 5 import java.util.Scanner; 6 public class JS { 7 public static void main(String[] args) { 8 Scanner in = new Scanner(System.in); 9 JS1 computing=new JS1(); 10 PrintWriter output = null; 11 try { 12 output = new PrintWriter("Caculator.txt"); 13 } catch (Exception e) { 14 } 15 int sum = 0; 16 17 for (int i = 1; i < 11; i++) { 18 int a = (int) Math.round(Math.random() * 100); 19 int b = (int) Math.round(Math.random() * 100); 20 int s = (int) Math.round(Math.random() * 3); 21 switch(s) 22 { 23 case 1: 24 System.out.println(i+": "+a+"/"+b+"="); 25 while(b==0){ 26 b = (int) Math.round(Math.random() * 100); 27 } 28 double c = in.nextDouble(); 29 output.println(a+"/"+b+"="+c); 30 if (c == (double)computing.division(a, b)) { 31 sum += 10; 32 System.out.println("正确"); 33 } 34 else { 35 System.out.println("错误"); 36 } 37 38 break; 39 40 case 2: 41 System.out.println(i+": "+a+"*"+b+"="); 42 int c1 = in.nextInt(); 43 output.println(a+"*"+b+"="+c1); 44 if (c1 == computing.multiplication(a, b)) { 45 sum += 10; 46 System.out.println("Ture"); 47 } 48 else { 49 System.out.println("False"); 50 } 51 break; 52 case 3: 53 System.out.println(i+": "+a+"+"+b+"="); 54 int c2 = in.nextInt(); 55 output.println(a+"+"+b+"="+c2); 56 if (c2 == computing.addition(a, b)) { 57 sum += 10; 58 System.out.println("Ture"); 59 } 60 else { 61 System.out.println("False"); 62 } 63 64 break ; 65 case 4: 66 System.out.println(i+": "+a+"-"+b+"="); 67 int c3 = in.nextInt(); 68 output.println(a+"-"+b+"="+c3); 69 if (c3 == computing.subtraction(a, b)) { 70 sum += 10; 71 System.out.println("Ture"); 72 } 73 else { 74 System.out.println("False"); 75 } 76 break ; 77 78 } 79 80 } 81 System.out.println("scores:"+sum); 82 output.println("scores:"+sum); 83 output.close(); 84 85 } 86 }
1 package vxdfuey; 2 3 public class JS1 4 { 5 private int a; 6 private int b; 7 public int addition(int a,int b) 8 { 9 return a+b; 10 } 11 public int subtraction(int a,int b) 12 { 13 if((a-b)<0) 14 return 0; 15 else 16 return a-b; 17 } 18 public int multiplication(int a,int b) 19 { 20 return a*b; 21 } 22 public int division(int a,int b) 23 { 24 if(b!=0) 25 return a/b; 26 else 27 return 0; 28 } 29 30 31 }
实验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语句块中。
抛出的异常类型尽可能明确。
不要压制异常,对于很少发生的异常,应该将 其关闭。
早抛出,晚捕获,尽量让高层次的方法通告用 户发生了错误