天天看點

菜雞自學JAVA坎坷路day.14(異常機制)

測試異常1:異常的基本用法

package TestException;

import java.io.File;
import java.io.FileNotFoundException;

/**
 * 測試一下Exception的使用
 * @author Wang
 *
 */

public class testException {
	public static void main(String[] args) {
		//int i = 1/0;   在這裡彙報一個這樣的異常:不需要我們捕獲;屬于uncheck異常Exception in thread "main" java.lang.ArithmeticException: / by zero
		//at TestException.testException.main(testException.java:10)
		
		//Computer c = null;   像這樣的uncheck的異常我們通常都會加一個if語句來限制一下   如下程式
		//c.start();  這個會報Exception in thread "main" java.lang.NullPointerException  空指針的異常;
		
		
//		Computer c  = null;
//		if(c!=null){
//			c.start();   //對象是null,調用了對象方法或屬性!
//		}
		
		//String str = "123abc";//像這樣的uncheck異常都是可以編譯過去的但是checked異常就需要我們去捕獲
		//Integer i = new Integer(str);這裡彙報這個異常:格式異常他隻能轉化整數類型的 java.lang.NumberFormatException:
		
		//Thread.sleep(3000);//這個是讓程式睡眠三秒鐘屬于checked異常需要我們去捕獲或者去抛出
		
		try {//捕獲這個異常  其實是因為他的源碼再定義的時候寫了抛出異常
			Thread.sleep(3000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}finally {
			System.out.println("aaa");//這個finally裡面的語句不論有沒有異常都會列印出來的
		}
		
		File f = new File("c:/Hello.txt");
		if(!f.exists()) {
			try {
				throw new FileNotFoundException("File cannot be found");//throw  這個是手動抛出異常
			}catch(FileNotFoundException e) {//catch語句try裡面一旦遇到異常就會執行這裡面的語句  執行玩這裡面的以後不會在回去執行try裡面的語句了;
				e.printStackTrace();
			}finally {
				System.out.println("aaa");//這個finally裡面的語句不論有沒有異常都會列印出來的
			}
		}

	}
}


class Computer{
	void start() {
		System.out.println("計算機啟動");
	}
}
           

測試異常2:File的異常

package TestException;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

/**
 * 測試File類的一些異常
 * @author Wang
 *
 */

public class testFile {
	public static void main(String[]  args) throws FileNotFoundException, IOException {
		String str;
		str = new testFile().openFile();
		System.out.println(str);
	} 
	
	String openFile() throws FileNotFoundException,IOException { //抛出兩個異常  抛出之後就是誰調用  誰就處理這個異常  或者繼續向上抛出  但是總是要有處理的  都不處理就是虛拟機來處理
		FileReader reader = new FileReader("d:/a.txt");
		char c = (char)reader.read();//每次讀一個字元;
		//System.out.println(c);
		return ""+c;
	}
}
           

測試異常3:異常的繼承機制

package TestException;

import java.io.FileNotFoundException;
import java.io.IOException;

/**
 * 測試異常抛出的範圍
 * @author Wang
 *
 */
public class testRange {
	class A {	
		public void method() throws IOException {	}
	}
	
	class B extends A {		public void method() throws FileNotFoundException {	}
	}
	
	class C extends A {		public void method() {	}
	}
	
//	class D extends A {		public void method() throws Exception {	}     //超過父類異常的範圍,會報錯!
//	}
	
	class E extends A {		public void method() throws IOException, FileNotFoundException {    }
	}
	class F extends A {		public void method() throws IOException, ArithmeticException {      }
	}
//	class G extends A {		public void method() throws IOException, ParseException {	}
//	}

}
           

注意:

子類抛出的異常範圍不能超過父類的異常範圍: