1. 程式人生 > 實用技巧 >第2章 fping、hping應用

第2章 fping、hping應用

  1. Exception 例外,異常
  2. 異常處理機制:丟擲異常,然後捕獲異常
  3. try-catch-finally示例
  4.         int a = 1;
            int b = 0;
            try {
                //監控區域
                System.out.println(a/b);
            }catch (ArithmeticException e){
                //catch的引數是想要捕獲的異常型別,可以寫多個catch,並且範圍大的要寫在範圍小的後面,一個異常只會被捕獲一次
                System.out.println("除數不能為0");
            }
    finally { //處理善後工作,也可以不寫,一般來關閉IO和資源 System.out.println("finally"); }

  5. throw-throws示例

  6.     public static void main(String[] args) {
            try {
                new Student().test(1,0);
            } catch (ArithmeticException e) {                                  //捕獲test()方法中丟擲的異常並處理,程式就不會停止
    System.out.println("除數為0"); } finally { System.out.println("結束"); } } public void test(int a,int b) throws ArithmeticException{ //假設方法中無法處理這個異常,再次丟擲異常 if (b==0){ throw new ArithmeticException(); //
    主動丟擲的異常,在方法中使用 } }

  7. IDEA中,ctrl+alt+t,再做出選擇即可快速建立捕獲異常的trycatchfinally語句
  8. 在多重catch塊後面,可以加一個catch(Exception)來處理可能被遺漏的異常
  9. 在catch捕獲後,儘量去處理異常,而非簡單的列印輸出
  10. 儘量新增finally語句塊去釋放佔用的資源,IO,Scanner
  11. (1)建立自定義異常類,繼承exception類即可,最好重寫toString方法(為了方便列印自己的異常資訊)

    (2)在方法中通過throw丟擲異常物件

    (3)如果在方法內沒有用try-catch捕獲並處理,那麼需要在方法的宣告處通過throws丟擲異常給方法呼叫者

    (4)呼叫者捕獲並處理異常

  12. 異常物件e就是該異常物件的toString()方法返回值(String型別)