实验九 异常、断言与日志

实验时间 2018-10-25

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

      }

}

 示例的更改思路与相应代码:

异常示例1:

增加判断分母是否为零的语句:

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

异常示例2:

更改思路

1. throws IOException :使用该语句抛出异常

2.try/catch语句块:捕获异常

3.将字节流改为字符流,读取文件内容

更改后代码:

package shiyan9;

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

public class ExceptionDemo2 {
    public static void main(String args[]) throws IOException 
     {
          try {

          File file = new File("text.txt");
          FileInputStream fis = new FileInputStream(file);
          BufferedReader in = new BufferedReader(new InputStreamReader(fis));
          String b;
          while((b=in.readLine())!=null)
          {
              System.out.print(b);
          }
          fis.close();
      }catch (Exception e) {
          e.printStackTrace();
      }
     }
}
ExceptionDemo2

相关文章:

  • 2022-03-01
  • 2021-09-30
  • 2022-01-12
  • 2021-10-13
  • 2021-10-17
  • 2022-12-23
  • 2021-09-25
  • 2021-11-18
猜你喜欢
  • 2021-06-13
  • 2021-09-25
  • 2021-12-15
  • 2021-06-06
  • 2021-05-20
  • 2021-12-21
  • 2021-07-20
相关资源
相似解决方案