201771010101 白玛次仁 《2018面向对象程序设计(Java)》第九周学习总结

实验九 异常、断言与日志

实验时间 2018-10-25

1.知识总结:

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

程序中出现的常见的错误和问题有:

用户输入错误

设备错误

物理限制

代码错误

Java把程序运行时可能遇到的错误分为两类:

1.非致命异常:通过某种修正后程序还能继续执行。这类错误叫异常。

2,致命异常:程序遇到了非常重要的不正常状态不能简单恢复执行。

Java中所有的异常类都直接或间接地继承于Throwable类。除内置异常类外,程序员可自定义异
常类。
 Java中的异常类可分为两大类:
- Error
- Exception
 Java将派生于Error类或RuntimeException类的所有异
常称为未检查异常,编译器允许不对它们做出异常处
理。
注意:“如果出现

RuntimeException异常,就一定是程序员的问题!
RuntimeException: 运行时异常类
IOException:输入输出异常类
Error很难恢复的严重错误,一般不由程序处理。
声明抛出异常:如果一个方法可能会生成一些异常,但是该方法并不确切知道何对这些异常事件进行处理,此时,这个方法就需声明抛出这些异常。

抛出异常对象通过throw语句来实现。
对于已存在的异常类,抛出该类的异常对象非常容
易,步骤是:
–找到一个合适的异常类;
–创建这个类的一个对象;
–将该对象抛出。
 一个方法抛出了异常后,它就不能返回调用者了。
自定义异常类:定义一个派生于Exception的直接
或间接子类。如一个派生于IOExce
程序运行期间,异常发生时,Java运行系统从异常
生成的代码块开始,寻找相应的异常处理代码,并
将异常交给该方法处理,这一过程叫作捕获。
l 某个异常发生时,若程序没有在任何地方进行该异
常的捕获,则程序就会终止执行,并在控制台上输
出异常信息。
l 若要捕获一个异常,需要在程序中设置一个
try/catch/ finally块:
–try语句括住可能抛出异常的代码段。
–catch语句指明要捕获的异常及相应的处理代码。
–finally语句指明必须执行的程序块。
catch块是对异常对象进行处理的代码;

断言:是程序的开发和测试阶段用于插入一些代码错误检
测语句的工具。
l 断言(assert)语法如下:
1、assert 条件
或者
2、assert 条件:表达式
这两个形式都会对布尔“条件”进行判断,如果判断结果
为假(false),说明程序已经处于不正确的状态下,系
统则抛出AssertionError,给出警告并且退出。在第二种
形式中,“表达式”会传入AssertionError的构造函数中
并转成一个消息字符

 

1、实验目的与要求

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

(2) 了解断言的用法

(3) 了解日志的用途;

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

2、实验内容和步骤

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

//异常示例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();

      }

}

异常后:

package 异常;//例1
public class ExceptionDemo1 {
    public static void main(String args[]) {
        int a=0;
        if(a==0) {
            System.out.println("除数为零!");
        }
        else {
            System.out.println(5 / a);

        }
    }
}
package 异常;//例2
import java.io.*;

public class ExceptionDemo2 {
    public static void main(String args[]) throws Exception 
   {
        FileInputStream fis=new FileInputStream("text.txt");//JVM自动生成异常对象
        int b;
        while((b=fis.read())!=-1)
        {
            System.out.print(b);
        }
        fis.close();
    }
}

 

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

测试程序1:

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

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

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

 

package stackTrace;

 

import java.util.*;

 

/**

 * A program that displays a trace feature of a recursive method call.

 * @version 1.01 2004-05-10

 * @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 + "):");

      Throwable t = new Throwable();

      StackTraceElement[] frames = t.getStackTrace();

      for (StackTraceElement f : frames)

         System.out.println(f);

      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)

   {

      Scanner in = new Scanner(System.in);

      System.out.print("Enter n: ");

      int n = in.nextInt();

      factorial(n);

   }

}

 

 

 

测试程序2

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

下列两个简答程序范例给出了两种异常处理的代码格式。在elipse IDE中编辑、调试运行源程序ExceptionalTest.java,将程序中的text文件更换为身份证号.txt,要求将文件内容读入内容,并在控制台显示;

掌握两种异常处理技术的特点。

//积极处理方式  

import java.io.*;

 

class ExceptionTest {

public static void main (string args[])

   {

       try{

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

       }

       catchFileNotFoundExcption e

     {   ……  }

……

    }

}

//消极处理方式

 

import java.io.*;

class ExceptionTest {

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

     {

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

     }

}

 

 

 

读入内容后:

package demo;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;

public class ExceptionTest {
    public static void main(String[] args) throws IOException {
        try {
            FileInputStream fis = new FileInputStream("身份证号.txt");
            BufferedReader in = new BufferedReader(new InputStreamReader(fis));
            String m, n = new String();
            while ((m = in.readLine()) != null) {
                n += m + "\n ";
            }
            in.close();
            System.out.println(n);

        } catch (FileNotFoundException e) {
            System.out.println("学生信息文件找不到");
            e.printStackTrace();
        } catch (IOException e) {
            System.out.println("学生信息文件读取错误");
            e.printStackTrace();
        }
    }
}


package demo;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;

public class ExceptionTest {
    public static void main(String[] args) throws IOException {
            FileInputStream fis = new FileInputStream("身份证号.txt");
            BufferedReader in = new BufferedReader(new InputStreamReader(fis));
            String m, n = new String();
            while ((m = in.readLine()) != null) {
                n += m + "\n ";
            }
            in.close();
            System.out.println(n);
  }

 

 

 

 

实验3: 编程练习

注:以下实验课后完成

练习2

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

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

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

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

package 异常;

 

import java.util.Scanner;

public class Demo {

public static void main(String[] args) {

// 用户的答案要从键盘输入,因此需要一个键盘输入流

Scanner in = new Scanner(System.in);

// 定义一个变量用来统计得分

int sum = 0;

for (int i = 0; i < 10; i++) {

 

// 随机生成两个10以内的随机数作为被除数和除数

int a = (int) Math.round(Math.random() * 100);

int b = (int) Math.round(Math.random() * 100);

System.out.println(a + "/" + b + "=");

// 定义一个整数用来接收用户输入的答案

int c = in.nextInt();

// 判断用户输入的答案是否正确,正确给10分,错误不给分

if (c == a / b) {

sum += 100;

System.out.println("恭喜答案正确");

}

else {

System.out.println("抱歉,答案错误");

}

}

//输出用户的成绩

System.out.println("你的得分为"+sum);

}

}

 

 

实验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);

    }

}

elipse下调试程序AssertDemo,结合程序运行结果理解程序;

注释语句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);
}

}

 

 

实验程序2

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

并掌握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();

    }

 }
 

 

 

实验总结:通过本周实验,初步了解了在java中异常的处理的基础技术。

上课老师的讲解加学长的指导和示例程序中更好了解了这次实验,

每次实验更好学会示例程序倒入和读懂程序,最重要是这章学的新内容用的上。

 

 

转载于:https://www.cnblogs.com/baimaciren/p/9865688.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值