JAVA異常處理機制(一)
阿新 • • 發佈:2018-12-01
異常處理機制try-catch
語法定義:
try{
//可能出現異常的程式碼片段
}catch(XXXException e){
//捕獲try中出現的XXXException後的處理操作程式碼
}
try-catch演示
public class Try_CatchDemo {
public static void main(String[] args) {
System.out.println("start");
try{
//String str = null;
//System.out.println(str.length());
//String str1 = "";
//System.out.println(str1.charAt(0));
String str2 = "a";
System.out.println(Integer.parseInt(str2)); //NumberFormatException 數字格式異常
/*
* 在try塊中出錯語句以下的程式碼都不會被執行
*/
System.out.println("!!!!!!");
}catch(NullPointerException e){
System.out .println("出現了空指標!");
}catch(StringIndexOutOfBoundsException e){
System.out.println("字串下標越界了!");
/*
* 應當有一個好習慣,在最後一個catch處捕獲Exception,防止一個未捕獲的異常導致程式中斷
*/
}catch(Exception e){
System.out.println("有異常");
}
System.out .println("end");
}
}
finally塊
finally塊是定義在異常處理機制的最後一塊.
它可以直接跟在try後面或者最後一個catch後面.
finally可以保證只要程式執行到了try塊中,那麼無論try塊中的語句是否會丟擲異常,
finally都確保其內容一定被執行.通常會將釋放資源等操作放在finally中
如流的關閉操作
public class FinallyDemo {
public static void main(String[] args) {
System.out.println("程式開始");
try {
String str = null;
System.out.println(str.length());
} catch (Exception e) {
System.out.println("出錯了!");
}finally{
System.out.println("finally!");
}
System.out.println("程式結束");
}
}
finally在IO中的使用
public class FinallyDemo2 {
public static void main(String[] args) {
FileOutputStream fos = null;
try {
fos = new FileOutputStream("fos.dat");
fos.write(1);
} catch (Exception e) {
e.printStackTrace();
} finally{
try {
if(fos!=null){
fos.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
上一串程式碼中close操作過於繁瑣
不過JDK7之後推出了一個新特性:自動關閉
java中實現了AutoCloseable介面的類,都可以被該特性自動關閉
public class AutoCloseable {
public static void main(String[] args) {
try(
FileOutputStream fos = new FileOutputStream("fos.dat"); //在try(){} 小括號中建立的物件將會被自動關閉
){
fos.write(1);
} catch (Exception e) {
e.printStackTrace();
}
}
}
finally常見面試題
請分別說明final,finally,finalize
final用於宣告屬性,方法和類,分別表示屬性不可交變,方法不可覆蓋,類不可繼承。
finally是異常處理語句結構的一部分,表示總是執行。
finalize是Object定義的方法,該方法是被GC執行的方法,
當一個物件即將被GC釋放前,GC會呼叫該方法. 呼叫該方法完畢後意為著該物件被釋放
public class FinallyDemo3 {
public static void main(String[] args) {
System.out.println(
test("0")+","+test(null)+","+test("") //3,3,3 程式執行到finally後將之前的結果覆蓋,其實下面的程式碼是不科學的
);
}
public static int test(String str){
try {
return str.charAt(0)-'0';
} catch (NullPointerException e) {
return 1;
} catch(Exception e){
return 2;
}finally{
return 3;
}
}
}