第一部分:理论基础部分总结

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

常见的几种错误:A:用户输入错误;B:设备错误;硬件出错;C:物理限制:磁盘满了,可用存储空间已被用完。

(2)异常的分类:

A:非致命异常:通过某种修正后程序还能继续执行。如:文件不存在,网络断开,无效的数组下标,磁盘满等。

B:致命性异常。程序用到了非常严重的不正常的状态,不能简单执行恢复。如:内存耗尽,系统内部错误。程序本身无法解决。

C:Java中所有异常类都直接或间接地继承于Throwable类。除內置异常类外,程序员可自定义异常类。A:Error类:描述了运行时系统的内部错误和资源耗尽;(很难恢复的严重错误,一般不由程序处理)B:Exception类:分为两分支一个分支派生于Runtime Exception;另一个分支包含其他异常。(程序设计或者实现上的问题,如数组越界等)。其他异常:通常是由环境引起的,并且可以被处理。

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

A:生命抛出异常在方法声明中用throws子句中来声明,throws子句可以同时指多个异常,说明该方法将不对这些异常进行处理,而是声明抛出它们。

B:用throws子句声明抛出异常:

—方法调用了一个抛出已检查异常的方法;

—程序运行过程中可能发生错误,并且利用throw语句抛出一个已检查异常对象

—程序出现错误

—Java虚拟机和运行时库出现的内部异常。

(4)创建异常类

A:自定义异常类:定义一个派生于Exception的直接或者间接类。自定义的异常类报货两个构造器:a:默认构造器b:带有详细描述信息的构造器。

二:捕获异常

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

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

(3)      若要捕获一个异常,需要在程序中设置一个 try/catch/ finally块:–try语句括住可能抛出异常的代码段。–catch语句指明要捕获的异常及相应的处理代码。–finally语句指明必须执行的程序块。

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

(5)        Catch子句:catch块是对异常对象进行处理的代码;每个try代码块可以伴随一个或多个catch语句,用于处理try代码块中所生成的格类异常事件;

(6)        Finally 子句:A:捕获异常的最后一步是通过finally语句为异常处理提供一个统一出口,使得控制流程在转到程序其他部分以前,能够对程序的状态做统一的管理;B:不管异常是否被捕获,finally子句中的代码都被执执行。

(7)        异常处理中分析堆栈跟踪元素:A:堆栈跟踪是程序执行中一个方法调用过程的列表,它包含了程序执行过程中的特定位置;B:可用Throwable类的printStack Trace方法访问堆栈跟踪的文本描述信息。

三:使用异常机制的建议:

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

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

第二部分:实验

1、实验目的与要求

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

(2) 了解断言的用法;

(3) 了解日志的用途;

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

2、实验内容和步骤

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

//异常示例1

public class ExceptionDemo1 {

public static void main(String args[]) {

int a = 0;

System.out.println(5 / a);

}

}

//异常示例2

import java.io.*;

public class ExceptionDemo2 {

public static void main(String args[])

{

FileInputStream fis=new FileInputStream("text.txt");//JVM自动生成异常对象

int b;

while((b=fis.read())!=-1)

{

System.out.print(b);

}

fis.close();

}

}

修改后:

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

  

import java.io.*;

public class ExceptionDemo2 {
public static void main(String args[]) throws IOException
{
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类的堆栈跟踪方法;

package stackTrace;

import java.util.*;

/**
* A program that displays a trace feature of a recursive method call.
* @version 1.10 2017-12-14
* @author Cay Horstmann
*/
public class StackTraceTest
{
/**
* Computes the factorial of a number
* @param n a non-negative integer
* @return n! = 1 * 2 * . . . * n
*/
public static int factorial(int n)
{
System.out.println("factorial(" + n + "):");
var walker = StackWalker.getInstance();
walker.forEach(System.out::println);
int r;
if (n <= 1) r = 1;
else r = n * factorial(n - 1);
System.out.println("return " + r);
return r;
} public static void main(String[] args)//程序入口
{
try (Scanner in = new Scanner(System.in))//try子句捕获异常
{
System.out.print("Enter n: ");
int n = in.nextInt();
factorial(n);
}
}
}

  

运行结果:

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

}

}

//积极处理方式  

	import java.io.*;
import java.io.BufferedReader;
import java.io.FileReader; class ExceptionTest { public static void main (String args[]) { File fis=new File("身份证号.txt"); try{ FileReader fr = new FileReader(fis);
BufferedReader br = new BufferedReader(fr);//创建对象
try {
String s, s2 = new String();
while ((s = br.readLine()) != null) {
s2 += s + "\n ";
}
br.close();
System.out.println(s2);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} }
}

 

//消极处理方式

  import java.io.*;
class ExceptionTest {
public static void main (String args[]) throws IOException
{
File fis=new File("身份证号.txt");
FileReader fr = new FileReader(fis);
BufferedReader br = new BufferedReader(fr);
String s, s2 = new String(); while ((s = br.readLine()) != null) {
s2 += s + "\n ";
}
br.close();
System.out.println(s2);
}
}

运行结果:

实验3: 编程练习

练习1:

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

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

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

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

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

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

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

注:以下实验课后完成

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.Scanner;
import java.util.Collections;//对集合进行排序、查找、修改等; public class Test {
private static ArrayList<Citizen> citizenlist; public static void main(String[] args) {
citizenlist = new ArrayList<>();
Scanner scanner = new Scanner(System.in);
File file = new File("E:/java/身份证号.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 id = linescanner.next();
String sex = linescanner.next();
String age = linescanner.next();
String birthplace = linescanner.nextLine();
Citizen citizen = new Citizen();
citizen.setName(name);
citizen.setId(id);
citizen.setSex(sex);
// 将字符串转换成10进制数
int ag = Integer.parseInt(age);
citizen.setage(ag);
citizen.setBirthplace(birthplace);
citizenlist.add(citizen); }
} 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.退出");
int nextInt = scanner.nextInt();
switch (nextInt) {
case 1:
Collections.sort(citizenlist);
System.out.println(citizenlist.toString());
break;
case 2:
int max = 0, min = 100;
int m, k1 = 0, k2 = 0;
for (int i = 1; i < citizenlist.size(); i++) {
m = citizenlist.get(i).getage();
if (m > max) {
max = m;
k1 = i;
}
if (m < min) {
min = m;
k2 = i;
}
}
System.out.println("年龄最大:" + citizenlist.get(k1));
System.out.println("年龄最小:" + citizenlist.get(k2));
break;
case 3:
System.out.println("出生地:");
String find = scanner.next();
String place = find.substring(0, 3);
for (int i = 0; i < citizenlist.size(); i++) {
if (citizenlist.get(i).getBirthplace().substring(1, 4).equals(place))
System.out.println("出生地" + citizenlist.get(i));
}
break;
case 4:
System.out.println("年龄:");
int yourage = scanner.nextInt();
int near = peer(yourage);
int j = yourage - citizenlist.get(near).getage();
System.out.println("" + citizenlist.get(near));
break;
case 5:
isTrue = false;
System.out.println("程序已退出!");
break;
default:
System.out.println("输入有误");
}
}
} public static int peer(int age) {
int flag = 0;
int min = 53, j = 0;
for (int i = 0; i < citizenlist.size(); i++) {
j = citizenlist.get(i).getage() - age;
if (j < 0)
j = -j;
if (j < min) {
min = j;
flag = i;
}
}
return flag;
}
}

  

public class Student implements Comparable<Student> {

   private String name;
private String number ;
private String sex ;
private int age;
private String province; public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getnumber() {
return number;
}
public void setnumber(String number) {
this.number = number;
}
public String getsex() {
return sex ;
}
public void setsex(String sex ) {
this.sex =sex ;
}
public int getage() { return age;
}
public void setage(int age) {
// int a = Integer.parseInt(age);
this.age= age;
} public String getprovince() {
return province;
}
public void setprovince(String province) {
this.province=province ;
} public int compareTo(Student o) {
return this.name.compareTo(o.getName());
} public String toString() {
return name+"\t"+sex+"\t"+age+"\t"+number+"\t"+province+"\n";
}
}

  运行结果:

练习2:

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

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

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

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

import java.io 

.FileNotFoundException;
import java.io .PrintWriter;
import java.util.Scanner;
public class jisuan{
public static void main(String[] args) {
Scanner in = new Scanner(System.in );
Caculator1 computing=new Caculator1();
PrintWriter output = null;
try {
output = new PrintWriter("Caculator.txt");
} catch (Exception e) {
}
int sum = 0; for (int i = 1; i < 11; i++) {
int a = (int) Math.round(Math.random() * 100);
int b = (int) Math.round(Math.random() * 100);
int s = (int) Math.round(Math.random() * 3);
switch(s)
{
case 1:
System.out.println(i+": "+a+"/"+b+"=");
while(b==0){
b = (int) Math.round(Math.random() * 100);
}
double c = in.nextDouble();
output.println(a+"/"+b+"="+c);
if (c == (double)computing.division(a, b)) {
sum += 10;
System.out.println("正确");
}
else {
System.out.println("错误");
} break; case 2:
System.out.println(i+": "+a+"*"+b+"=");
int c1 = in.nextInt();
output.println(a+"*"+b+"="+c1);
if (c1 == computing.multiplication(a, b)) {
sum += 10;
System.out.println("正确");
}
else {
System.out.println("错误");
}
break;
case 3:
System.out.println(i+": "+a+"+"+b+"=");
int c2 = in.nextInt();
output.println(a+"+"+b+"="+c2);
if (c2 == computing.addition(a, b)) {
sum += 10;
System.out.println("正确");
}
else {
System.out.println("错误");
} break ;
case 4:
System.out.println(i+": "+a+"-"+b+"=");
int c3 = in.nextInt();
output.println(a+"-"+b+"="+c3);
if (c3 == computing.subtraction(a, b)) {
sum += 10;
System.out.println("正确");
}
else {
System.out.println("错误");
}
break ; } }
System.out.println("scores:"+sum);
output.println("scores:"+sum);
output.close(); }
}

  运行结果:

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

//断言程序示例
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);
}
}

  运行结果:

/断言程序示例
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  掌握断言的使用特点及用法。

实验程序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;
var 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(() ->
{
var windowHandler = new WindowHandler();
windowHandler.setLevel(Level.ALL);
Logger.getLogger("com.horstmann.corejava").addHandler(windowHandler); var 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
var menuBar = new JMenuBar();
setJMenuBar(menuBar); var menu = new JMenu("File");
menuBar.add(menu); var openItem = new JMenuItem("Open");
menu.add(openItem);
openItem.addActionListener(new FileOpenListener()); var 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
var 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();
var 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();
}
}

  运行结果:

实验程序3:

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

按课件66-77内容练习

①条件断点 –在Eclipse Java 编辑区的行头双击就会得到一个断点, 代码会运行到此处时停止。 –条件断点,顾名思义就是一个有一定条件的断点,只有满 足了用户设置的条件,代码才会在运行到断点处时停止。 –在断点处点击鼠标右键,选择后一个“Breakpoint Properties”.

②变量断点–断点不仅能打在语句上,变量也可以接受断点:

–上图就是一个变量的打的断点,在变量的值初 始化,或是变量值改变时可以停止,当然变量 断点上也是可以加条件的,和上面的介绍的条 件断点的设置是一样的。

③方法断点 –方法断点就是将断点打在方法的入口处:
–方法断点的特别之处在于它可以打在JDK的源 码里,由于JDK在编译时去掉了调试信息,所 以普通断点是不能打到里面的,但是方法断点 却可以,可以通过这种方法查看方法的调用栈。

④异常断点 –经常遇见一些异常,然后程序就退出来了,要找到 异常发生的地方就比较难了,还好可以打一个异常 断点。
–上图中我们增加了一个NullPointException的异常 断点,当异常发生时,代码会停在异常发生处,定 位问题时应该比较有帮助。

⑤重新调试
–这种调试的回退不是万能的,只能在当前线程的栈帧 中回退,也就说多只能退回到当前线程的调用的开 始处。 –回退时,请在需要回退的线程方法上点右键,选择 “Drop to Frame”。

实验总结:本周学习了第七章的知识,异常有致命性异常和非致命性异常,后者,可以通过程序员的相关操作可以处理,通过学习可以知道利用try子句捕获异常代码的范围,它的执行过程中生成异常对象并抛出异常,不论代码块中是否有异常,finally块中的语句都执行;验证了积极处理方式和消极处理方式,分别用throws子句和try子句;总而言之理论知识可以通过课件基本理解了相关概念,但是自己的实验的动手能力还需要大程度地提高。

最新文章

  1. pl/sql里的exists和in的差别
  2. 拓扑排序(三)之 Java详解
  3. 图表Echarts的使用
  4. 聊一聊google的Knowledge Graph
  5. 寒假D3 A Find the Lost Sock
  6. 使用Adreno Profiler分析android游戏
  7. [转]EasyUI——常见用法总结
  8. 网络文件常常提到类似&quot;./run.sh&quot;的数据,这个命令的意义是什么?
  9. PHP 网站保存快捷方式的实现代码
  10. cogs_396_魔术球问题_(最小路径覆盖+二分图匹配,网络流24题#4)
  11. ajax 操作全局监测,用户session失效
  12. 使用Eclipse进行Javaweb项目开发时,如何设置外置浏览器Chrome
  13. Python 第五天
  14. android动画源码合集、动态主题框架、社交app源码等
  15. ASP.NET Core中使用GraphQL - 第八章 在GraphQL中处理一对多关系
  16. 【Spark篇】---Spark解决数据倾斜问题
  17. Queue 队列的使用
  18. html5 简介
  19. Python基本数据类型——元组和集合
  20. 浅析C语言的变量

热门文章

  1. 细数阿里云在使用 Docker 过程中踩过的那些坑
  2. Netty(二):数据在ChannelPipeline中的流经
  3. 如何设计scalable 的系统 (转载)
  4. apache、nginx配置自签名证书
  5. LeetCode 98. 验证二叉搜索树 | Python
  6. spring学习笔记(六)自定义spring-boot-starter(2)
  7. Linux编程实现递归查找文件
  8. OpenCV Error: Unspecified Error(The Function is not implemented)
  9. Redis学习笔记(二) 链表
  10. C语言进阶_分支语句