實驗九 異常、斷言與日誌java
實驗時間 2018-10-25程序員
1.知識總結:編程
異常:在程序的執行過程當中所發生的異常事件,它中斷指令正常執行。app
程序中出現的常見的錯誤和問題有:less
用戶輸入錯誤dom
設備錯誤函數
物理限制工具
代碼錯誤測試
Java把程序運行時可能遇到的錯誤分爲兩類:this
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)語法以下:
一、assert 條件
或者
二、assert 條件:表達式
這兩個形式都會對布爾「條件」進行判斷,若是判斷結果
爲假(false),說明程序已經處於不正確的狀態下,系
統則拋出AssertionError,給出警告而且退出。在第二種
形式中,「表達式」會傳入AssertionError的構造函數中
並轉成一個消息字符
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(); } } |
異常後:
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:
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.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語言的異常處理有積極處理方法和消極處理兩種方式;
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"); } } |
|
讀入內容後:
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:
l 編寫一個計算器類,能夠完成加、減、乘、除的操做;
l 利用計算機類,設計一個小學生100之內數的四則運算練習程序,由計算機隨機產生10道加減乘除練習題,學生輸入答案,由程序檢查答案是否正確,每道題正確計10分,錯誤不計分,10道題測試結束後給出測試總分;
l 將程序中測試練習題及學生答題結果輸出到文件,文件名爲test.txt;
l 在以上程序適當位置加入異常捕獲代碼。
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); } } |
l 在elipse下調試程序AssertDemo,結合程序運行結果理解程序;
l 註釋語句test1(-5);後從新運行程序,結合程序運行結果理解程序;
l 掌握斷言的使用特色及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:
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;
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中異常的處理的基礎技術。
上課老師的講解加學長的指導和示例程序中更好了解了此次實驗,
每次實驗更好學會示例程序倒入和讀懂程序,最重要是這章學的新內容用的上。