1. 程式人生 > >Java學習日常(異常處理)

Java學習日常(異常處理)

學習內容

Java 的異常處理方法;
  • 產生的原因有兩點:
    1.編譯時的錯誤;
    2.執行時的異常(不允許發生);
  • 處理方法:
    使用try catch;
  • 程式碼驗證
public class Demo1 {
    public static void main(String[] args) {
        String str = "abc";
        str = null;
        fun1("abc", null);
    }

    public static int div(int m, int n) {
        int
k = m / n; return k; } public static void fun1(String str, String subStr) { try { System.out.println("11111111"); int i = 10 / 0; if (str.indexOf(subStr) >= 0) { System.out.println("存在子串"); } else { System.out
.println("不存在子串"); } System.out.println("end"); } catch (Exception ex) { System.out.println("程式出現錯誤"); ex.printStackTrace(); System.out.println("#"+ex.getMessage()); }
  • 資源回收
    使用finally來實現資源回收
  • 程式碼驗證
finally {
            // 一定會被執行的程式碼塊
System.out.println("finally"); }
  • 自定義的建立一個異常物件
throw new Exception
  • 在方法定義的後面顯式的宣告方法是有異常的,呼叫該方法的程式是要顯式的處理異常,後者也可以再次向上丟擲,該不處理異常。
throws Exception
異常堆疊資訊

1.異常類
2.異常提示資訊:getMessage()
3.異常所在的程式碼位置:自下而上是異常出現的程式碼所在方法的呼叫順序的先後。

學習總結

對於今天的一天的學習還算是很繁忙的,自習的時間回顧了前面所學的知識內容,時間對於現在的我而言是非常緊迫的,有可能是自己的學習方法的問題,總感覺時間不夠用,東西學不完。