Java學習筆記35(異常)

來源:互聯網
上載者:User

標籤:row   fun   heap   nbsp   java學習筆記   div   extend   void   負數   

代碼在運行中發生的問題就是異常

java中把多種異常封裝多個類,當程式出現問題時候,就會建立異常類對象並且拋出相關資訊

 

異常體系:

Throwable類是Java中所有錯誤或異常的父類

Throwable的子類Error類是所有錯誤的父類

Throwable的另一個子類Exception類是所有異常的父類

在開發中,相對來說,我們並不關心錯誤,而更關心異常

異常和錯誤的區別(通俗解釋):

異常:相當於一個人感冒了,吃藥睡覺等進行相應的操作即可痊癒,不修改代碼處理掉異常,程式還可以執行

錯誤:相當於一個人得了絕症,無法治癒,必須修改代碼,程式才可以執行

所以可以這樣理解:我們並不關心患了絕症的人,而會想方法去治癒得了小病的人

樣本:‘

package demo;public class Demo {    public static void main(String[] args) {        function1();        function2();    }    public static void function1(){        //異常        int[] arr = {1,2};        System.out.println(arr[3]);        //輸出:        //Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3        //at demo.Demo.function1(Demo.java:11)        //at demo.Demo.main(Demo.java:5)    }    public static void function2(){        //錯誤        int[] arr = new int[666666666];        System.out.println(arr);        //輸出:        //Exception in thread "main" java.lang.OutOfMemoryError: Java heap space        //at demo.Demo.function2(Demo.java:19)        //at demo.Demo.main(Demo.java:6)    }}

 

一旦異常被拋出了,後邊的程式都不會執行,因此要想辦法解決這個問題

 

異常中的關鍵字throw:

寫一段代碼,存在null 指標異常

package demo;public class ExceptionDemo {    public static void main(String[] args) {        int [] arr = null;        function(arr);    }    public static int function(int[] arr){        int i = arr[arr.length-1];        return i;    }}

加入throw關鍵字,拋出異常:

package demo;public class ExceptionDemo {    public static void main(String[] args) throws Exception {        int [] arr = null;        int i = function(arr);        System.out.println(i);    }    public static int function(int[] arr) throws Exception{        //如果方法中有異常,需要在方法上聲明:throws Exception        //拋出的類型和聲明的異常類應當一致        //main調用這個方法,也需要加入聲明        if(arr == null){            //拋出異常,告訴調用者            //手動拋出異常            throw new Exception("傳遞數組不存在");        }        if(arr.length == 0){            throw new Exception("傳遞的數組中沒有元素");        }        int i = arr[arr.length-1];        return i;    }}/*輸出:Exception in thread "main" java.lang.Exception: 傳遞數組不存在at demo.ExceptionDemo.function(ExceptionDemo.java:16)at demo.ExceptionDemo.main(ExceptionDemo.java:6)*/

這裡注意,如果是運行時異常(RuntimeException),不需要throws聲明 ,

而且如果發生這種異常,那麼必須改代碼,否則代碼無意義

 

try  catch方法異常處理:

package demo;public class ExceptionDemo {    public static void main(String[] args) {        int[] arr = null;        try {            int i = function(arr);            System.out.println(i);        } catch (NullPointerException ex) {            System.out.println(ex);        } catch (ArrayIndexOutOfBoundsException ex) {            System.out.println(ex);        }        System.out.println("結束");    }    public static int function(int[] arr) throws NullPointerException, ArrayIndexOutOfBoundsException {        if (arr == null) {            // 手動拋出null 指標異常            throw new NullPointerException("數組不存在");        }        if (arr.length < 6) {            // 手動拋出數組索引越界異常            throw new ArrayIndexOutOfBoundsException("數組沒有6索引");        }        return arr[6];    }}/*輸出:java.lang.NullPointerException: 數組不存在結束 */

這裡發現,雖然程式有異常,但是依然執行後面的代碼,這就是異常處理

 

catch的順序:

平級:

package demo;/* * catch處理的注意事項: *   有順序
* 當異常是平級的時候,即沒有繼承關係的時候,沒有順序限制 */public class ExceptionDemo { public static void main(String[] args) { try { } catch (NullPointerException e) { } catch (ArrayIndexOutOfBoundsException e) { } }}

有繼承關係:

package demo;//有繼承關係:越進階的寫在越靠後public class ExceptionDemo {    public static void main(String[] args) {        try {                    } catch (NullPointerException ex) {        } catch (RuntimeException ex) {                    } catch (Exception ex){                    }    }}

 

 

finally:

package demo;//finally:必須執行//是否有異常都會執行public class ExceptionDemo {    public static void main(String[] args) {        try {            function(1);        } catch (Exception ex) {            System.out.println(ex);        } finally {            System.out.println("代碼必須執行");        }    }    public static void function(int a) throws Exception {        if (a == 0) {            throw new Exception();        }        System.out.println(a);    }}//無論傳入什麼,都會輸出:代碼必須執行

 

注意事項:

1.父類的方法如果拋出異常,子類重寫後可以不拋出異常,但是子類如果要拋出異常,這個異常的繼承關係不能大於父類的異常

 

自訂異常:

有時候需要一些自訂的異常,這裡做一個樣本:

package demo;public class FuShuException extends RuntimeException {    public FuShuException(String string){        super(string);    }    public FuShuException(){}}
package demo;//設定一個情景,計算兩門成績的平均數,不能為負數//如果是一個負數,就拋出異常public class ExceptionDeno {    public static void main(String[] args) throws FuShuException {        try {            int i = function(10, 97);            System.out.println(i);        } catch (FuShuException ex) {            ex.printStackTrace();        }    }    public static int function(int a, int b) throws FuShuException {        if (a < 0 || b < 0) {            throw new FuShuException("成績不為負");        }        int sum = a + b;        return sum / 2;    }}

 

Java學習筆記35(異常)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.