Java錯誤和異常解析


Java錯誤和異常解析


錯誤和異常

在Java中, 根據錯誤性質將運行錯誤分為兩類: 錯誤和異常. 在Java程序的執行過程中, 如果出現了異常事件, 就會生成一個異常對象. 生成的異常對象將傳遞Java運行時系統, 這一異常的產生和提交過程稱為拋棄(throw)異常.當Java運行時系統得到一個異常對象時, 它將會沿着方法的調用棧逐層回溯, 尋找處理這一異常的代碼. 找到能夠處理這類異常的方法后, 運行時系統把當前異常對象交給這個方法進行處理, 這一過程稱為捕獲(catch)異常.

Throwable

類是 Java 語言中所有錯誤或異常的超類, 它的兩個子類是Error和Exception

Error

Throwable 的子類, 用於指示合理的應用程序不應該試圖捕獲的嚴重問題. 大多數這樣的錯誤都是異常條件. 雖然 ThreadDeath 錯誤是一個"正規"的條件, 但它也是 Error 的子類, 因為大多數應用程序都不應該試圖捕獲它. 在執行該方法期間, 無需在其 throws 子句中聲明可能拋出但是未能捕獲的 Error 的任何子類, 因為這些錯誤可能是再也不會發生的異常條件. Error類包括一些嚴重的程序不能處理的系統錯誤類, 如內存溢出, 虛擬機錯誤, 棧溢出等. 這類錯誤一般與硬件有關, 與程序本身無關, 通常由系統進行處理, 程序本身無法捕獲和處理.
1.OutOfMemoryError內存溢出一般是出現在申請了較多的內存空間沒有釋放的情形

//java.lang.OutOfMemoryError  -Xmx150m
try {
	byte[] b = new byte[1024*1024*600];
} catch (OutOfMemoryError e) {
	e.printStackTrace();
}

運行時,設置jvm最大的heap內存150m,此時申請600m的內存,因此會報error

java.lang.OutOfMemoryError: Java heap space

2.StackOverflowError
堆棧溢出錯誤. 當一個應用遞歸調用的層次太深而導致堆棧溢出時拋出該錯誤.

public static void main(String[] args) {
	method();
}
public static void method() {
	while (true) {
		method();
	}
}

無限次的遞歸調用出現

Exception in thread "main" java.lang.StackOverflowError
Exception

類及其子類是 Throwable 的一種形式, 它指出了合理的應用程序想要捕獲的條件. 有些異常在編寫程序時無法預料的, 如中斷異常, 非法存取異常等. 為了保證程序的健壯性, Java要求必須對這些可能出現的異常進行捕獲, 並對其進行處理. Exception的除RuntimeException類的對象, 都是可檢查的異常(Checked exception), Checked exception需要明確聲明.

public class Exception extends Throwable

The class Exception and its subclasses are a form of Throwable that indicates conditions that a reasonable application might want to catch.

The class Exception and any subclasses that are not also subclasses of RuntimeException are checked exceptions. Checked exceptions need to be declared in a method or constructor's throws clause if they can be thrown by the execution of the method or constructor and propagate outside the method or constructor boundary.

RuntimeException

類是Exception類的子類. RuntimeException是那些可能在 Java 虛擬機正常運行期間拋出的異常的超類, 可能在執行方法期間拋出但未被捕獲的RuntimeException 的任何子類都無需在 throws 子句中進行聲明. 它是Exception的子類. 常見的運行時異常:

try {
	String str = new String("AA");
	str = null;
	System.out.println(str.length());
} catch (NullPointerException e) {
	e.printStackTrace();
	System.out.println("出現空指針的異常了");
}

try {
	Object obj = new Date();
	String str = (String) obj;
} catch (ClassCastException e) {
	System.out.println("出現類型轉換的異常了");
} catch (Exception e) {
	e.printStackTrace();
} finally {
	System.out.println("處理完異常后的邏輯");
}

try {
	int i = 10;
	System.out.println(i / 0);
} catch (ArithmeticException e) {
	System.out.println("算術異常"+e.getMessage());
}

try {
	int[] i = new int[10];
	System.out.println(i[-10]);
} catch (ArrayIndexOutOfBoundsException e) {
	System.out.println("數組下標越界的異常!");
}
IOExeption

類是Exception類的子類, 從一個不存在的文件中讀取數據, 越過文件結尾繼續讀取, 連接一個不存在的URL

FileInputStream fis = null;
try {
	fis = new FileInputStream(new File("hello1.txt"));
	int b;
	while ((b = fis.read()) != -1) {
		System.out.print((char) b);
	}
} catch (FileNotFoundException e1) {
	System.out.println("文件找不到了!");
} catch (IOException e1) {
	System.out.println(e1.getMessage());
} finally {
	try {
		fis.close();
	} catch (IOException e) {
		e.printStackTrace();
	}
}

throws用來聲明一種可能要拋出的異常類型, throw用來拋出一個異常對象. Exception體系包括RuntimeException體系和其他非RuntimeException的體系, RuntimeException是unchecked的, 而其他的Exception是checked, checked的意思就是可以通過try catch finally來捕獲.

異常的打印發生后, 語句可以執行嗎?

package com.test;

import java.util.ArrayList;
import java.util.List;

/**
 * RuntimeException, 發生了異常,就無法執行后續的代碼
 * 只要是非RuntimeException, 在exception塊之外,發生異常仍然可以執行后續的代碼,在exception之中,
 * 無法執行,塊就是指的包裹異常的部分
 * https://www.cnblogs.com/wangyingli/p/5912269.html
 * https://www.cnblogs.com/panxuejun/p/6837910.html
 * https://blog.csdn.net/kingzone_2008/article/details/8535287
 * https://blog.csdn.net/weixin_34319374/article/details/85889019
 */
public class MyException
{
    /**
     * 代碼1
     */
    private static List<String> ls = new ArrayList<>();

    // 不需要,直接報錯
    public static void add(String element, List ll)
    {
        ll.add(element);
        int size = ll.size();
        if (size >= 2)
        {
            throw new RuntimeException("順序表已滿,無法添加");
            // return; //無法執行
        }
    }

    /**
     * 代碼2
     */
    public static void test2() throws Exception
    {
        throw new Exception("參數越界。。。。。");
        //System.out.println("異常后"); // 編譯錯誤,「無法訪問的語句」
    }

    public static void test3() throws Exception
    {
        /**
         * 代碼3
         */
        if (true)
        {
            throw new Exception("參數越界33333333333");
            // System.out.println("3,3,3,3,3"); // 不會執行, 拋出了 Exception聲明, 整個方法都是塊
        }
        System.out.println("異常后"); // 拋出異常,不會執行
    }

    public static void test4()
    {
        /**
         * 代碼4
         */
        if (true)
        {
            try
            {
                throw new Exception("參數越界33333333333");
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }
            System.out.println("4=========="); // 會執行, try,catch是它的塊
        }
        System.out.println("異常后"); // 會執行
    }

    public static void main(String[] args)
    {
        // 1
        //        add("xx", ls);
        //        add("xx", ls);
        //        add("xx", ls);
        //        System.out.println(1);  // 無法執行

        // 2
        //        try
        //        {
        //            test2();
        //        }
        //        catch (Exception e)
        //        {
        //            e.printStackTrace();
        //        }
        //        System.out.println(2); //可以執行

        // 3
        //        try
        //        {
        //            test3();
        //        }
        //        catch (Exception e)
        //        {
        //            e.printStackTrace();
        //        }
        //        System.out.println(3);

        // 4
        try
        {
            test4();
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        System.out.println(4);
    }
}

ref:
1.詳解Java異常Throwable、Error、Exception、RuntimeException的區別, 2.RuntimeException和Exception區別, 3.Throwable、Error、Exception、RuntimeException 區別 聯系


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM