一些基礎知識:
1.try程式碼片段包含可能產生例外的代碼;
2.try程式碼片段後跟有一個或多個程式碼片段;
3.每個catch程式碼片段聲明其能處理的一種特定的異常並提供處理的方法;
4.當異常發生時,程式會終止當前的流程,根據擷取異常的類型去執行相應的catch程式碼片段,有多個合格catch時,只執行第一個;
5.finally段的代碼無論是否發生異常都會執行。
6.在一個try語句塊中,基類異常的捕獲語句不可以寫在子類異常捕獲語句的上面。
看一個例子:
/**<br /> * @author Lansine<br /> *<br /> */<br />public class T1 {</p><p>/**<br /> * @param args<br /> */<br />public static void main(String[] args) {<br />String s = "1";<br />try {<br />s = "2";<br />System.out.println(s);<br />if (s == "2")<br />throw new Exception("h");<br />} catch (Exception e) {<br />s = "3";<br />System.out.println(s);<br />} finally {<br />s = "4";<br />System.out.println(s);<br />}<br />s = "5";<br />System.out.println(s);</p><p>}</p><p>}
輸出的結果是2,3,4,5 (這裡的逗號只用於顯示)。上述語句非常清楚,但是在上述結構中加上return,就變得有些複雜了,如
/**<br /> * @author Lansine<br /> *<br /> */<br />public class T2 {</p><p>/**<br /> * @param args<br /> */<br />public static void main(String[] args) {<br />String s = "1";<br />try {<br />s = "2";<br />System.out.println(s);<br />return;<br />} catch (Exception e) {<br />s = "3";<br />System.out.println(s);<br />} finally {<br />s = "4";<br />System.out.println(s);<br />}<br />s = "5";<br />System.out.println(s);</p><p>}</p><p>}
輸出的結果是2,4也就是說在try結構中,雖然使用了return語句強制函數返回,不再往下執行,但實現上finally中的還是執行了。但除了finally外的其它語句不再被執行。
一個更流行的例子是:
import java.io.*;</p><p>/**<br /> * @author Lansine<br /> *<br /> */</p><p>public class Mine {<br />public static void main(String argv[]){<br />Mine m = new Mine();<br />try {<br />System.out.println(m.amethod());<br />} catch (Exception e) {<br />// TODO 自動產生 catch 塊<br />//e.printStackTrace();<br />System.out.println("我知道了");<br />}<br />System.out.println("finished");<br />}</p><p>public int amethod()throws Exception {<br />try {<br />FileInputStream dis = new FileInputStream("Hello.txt"); // 1,拋出異常<br />System.out.println("異常發生之後");<br />} catch (Exception ex) {<br />System.out.println("No such file found"); // 2.catch捕捉異常,並執行<br />//throw new Exception("上面處理");<br />return -1; // 4,return 返回<br />} finally {<br />System.out.println("Doing finally"); // 3.finally一定會執行,在return之前。<br />}</p><p>System.out.println("在代碼後面");</p><p>return 0;<br />}<br />}
結果是:
No such file found<br />Doing finally<br />-1<br />finished<br />
如果在catch塊中拋出異常,則結果為:
No such file found<br />Doing finally<br />我知道了<br />finished
注意:如果異常往上拋直到main函數還沒有被catch處理的話,程式將被異常終止。