1. 異常關鍵字---try catch finally
public abstract class TryCatchFinally {
/**
* 異常處理方法之一,捕獲異常
* try catch finally
* try:可能出現異常的邏輯語句,一旦出現異常則停止程序運行,異常被捕獲
* catch:出現異常,捕獲,拋出異常,需要處理
* finally:總會被執行,放置關閉資源的代碼,節約內存
*/
public static void main(String[] args) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
System.out.println("finally內的程序總會被執行,用於釋放緩存,節省內存");
}
}
}
2. try catch finally return 的執行順序
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
/**
* try catch finally return 的執行順序
* {1.執行 try catch 給返回值賦值
* 2.執行finally
* 3.返回值}
* finally中不能使用return 否則只會返回finally內的返回值,原來的返回值被覆蓋
* @author Administrator
*
*/
public class TestException03 {
public static void main(String[] args) {
String str = new TestException03().openFile();
System.out.println(str);
}
String openFile(){
System.out.println("aaa");
try {
FileInputStream fis = new FileInputStream("E:/new folder/a.txt");
int a = fis.read();
System.out.println("bbb");
return "step1";
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
System.out.println("catching");
e.printStackTrace();
return "step2";
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return "step3";
}finally{
System.out.println("finally");
// return "fff";
}
}
}