JavaSE: 異常的拋出

基本概念:ide

  在某些特殊狀況下,有些異常不能處理,或者不便於處理時,就能夠 將 該異常 轉移給對象

  該方法的 調用者, 這種方法 就叫 異常的拋出。it

  當方法執行時出現異常,則底層生成一個 異常類對象 拋出,此時異常代碼後續的代碼 就再也不執行。io

 

語法格式:class

  訪問權限 返回值類型 方法名稱(形參列表) throws 異常類型1, 異常類型2,... { 方法體;}test

  如:權限

    public void show() throws IOException {語法

    }方法

 

示例:經驗

 

public class ExceptionThrowsTest {

 

  public static void show throws IOException(){

    FileInputStream fis = new FileInputStream("d:/a.txt"); // 發生異常

    printIn ("我想看看你拋出異常後是否繼續向下執行"); // 沒有執行

    fis.close();

  }

  // 不建議在main方法中拋出異常, 由於 JVM的負擔已經很重了

  public static void main(String[] args) /* throws IOException */ {

    try {

      show();

    } catch (IOException e) {

      e.printStackTrace();

    }

  }

}

 

異常拋出的補充

示例:

 

// 父類

public class ExceptionMerhod {

  

  public void show() throws IOException {

 

  }

}

 

// 子類

public class SubExceptionMethod extends ExceptionMethod {

 

  @Override

  // public void show() throws IOException { }  //  子類重寫的方法能夠拋出和父類中方法同樣的Exception

  // public void show() throws FileNotFoundException { }  //  子類重寫的方法能夠拋出更小的Exception

  // public void show() {}  //  子類能夠 不拋出異常

  // public void show() throws ClassNotLoadedException {}  //  不能夠拋出平級不同的異常 

  // public void show() throws Exception {}  //  不能夠拋出更大的異常  (」孩子不能比爹更壞「)

}

 

經驗:

  1.  若父類中被重寫的方法沒有拋出異常時,則子類中重寫的方法只能進行異常的捕獲處理。 (由於子類不能拋出更大的異常)

  2.  若一個方法內部又以遞進方式分別調用了幾個好幾個其餘方法,則建議這些方法內可使用拋出的方法處理到外面一層進行捕獲方式處理。

 

經驗2 - 示例:

public class ExceptionThrowsTest {

 

  public static void show throws IOException(){

    FileInputStream fis = new FileInputStream("d:/a.txt"); // 發生異常

    printIn ("我想看看你拋出異常後是否繼續向下執行"); // 沒有執行

    fis.close();

  }

 

  public static void test1() throws IOException { //  拋到外面一層 - show()

    show();

  }

 

  public static void test2() throws IOException { //  拋到外面一層 - test1()

    test1();

  }

 

  public static void test3() throws IOException { //  拋到外面一層 - test2()

    test2();

  }

 

  main(){

    try{

      test3();

    }

    catch(IOException e){

      e.printStackTrace();

    }

  }

}

相關文章
相關標籤/搜索