java 異常詳解及應用實例
java 異常
異常的使用實例(異常分類:Error(是由JVM調用系統(tǒng)底層發(fā)生的,只能修改代碼) 和 Exception(是JVM發(fā)生的,可以進行針對性處理))
1.如果一個方法內可能出現(xiàn)異常,那么可以將異常通過throw的方式new 出相應的異常類,并在方法上 聲明throws可能拋出的異常類拋給調用者,調用者可以進行異常捕獲,或者繼續(xù)拋出異常由 上層調用者繼續(xù)處理, 如果整個過程都沒有將異常進行任何處理,那么將由JVM虛擬機進行默認的處理
2.調用者可以對異常進行try()catch(){}的異常處理, 也可以繼續(xù)在方法后面throws該異常,catch代碼塊中 如果不處理也可以進行throw該異常
3.運行時異常RuntimeException可以不進行顯式的異常聲明
4.如果父類中的方法拋出了異常,如果子類對方法進行重寫后也拋出異常,那么該異常必須不能大于父類的異常類, 如果父類中方法沒有拋出異常,而子類中覆蓋的方法卻拋出了異常,那么此時只能進行try catch來捕獲此異常,但是也可以將此異常在catch代碼塊中throw new RuntimeExcetion()進行拋出,這樣方法不用進行throws聲明
5.很多時候異常并不需要調用者進行處理,調用者不一定具有處理能力
6.異常應該包裝成上層調用者可以識別的異常類型,面向不同的調用者,報告不同的異常信息,否者調用者不知道如何處理該異常
在開發(fā)中這點十分重要
7.finally代碼塊中常常進行資源的釋放及關閉操作,對于打開的資源應該進行反方向的關閉操作,因為資源可能存在依賴性
8.如果不進行聲明異常,那么目的是不讓調用者進行處理,讓調用者的程序停止,這樣必須修改錯誤代碼
public class ExceptionDemo {
public static void main(String[] args) {
//OutOfMemoryError內存溢出錯誤,
int[] i = new int[1024*1024*1024];
System.out.println(i[1]);
//ArrayIndexOutOfBoundsException索引越界異常
int[] s = new int[2];
System.out.println(s[2]);
Calc calc = new Calc();
//假如我們在這里捕獲異常
try {
calc.run(4, 0);
calc.run(4, -1);
} catch (NegativeException e) {//必須先拋出異常的自定義子類
e.printStackTrace();
System.out.println(e.getMessage());
//throw e;//可以繼續(xù)將此異常拋出
} catch (ArithmeticException e){//拋出自定義異常類的父類
e.printStackTrace();
System.out.println(e.getMessage());
//throw e;
} finally {
System.out.println("finally肯定會執(zhí)行到");
}
//如果上面進行了異常捕獲,那么代碼可以繼續(xù)執(zhí)行,否者代碼不能繼續(xù)執(zhí)行
System.out.println("可以執(zhí)行到!");
try {
calc.run(4, -1);
} catch (NegativeException e) {
e.printStackTrace();
System.out.println(e.getMessage());
return;
} finally {
System.out.println("肯定會執(zhí)行的");
}
System.out.println("執(zhí)行不到了");//執(zhí)行不到此行代碼
}
}
/**
* 自定義異常
*/
class NegativeException extends ArithmeticException{
public NegativeException() {
}
public NegativeException(String msg) {
super(msg);
}
}
interface AA{
public abstract void method();
}
class Calc implements AA{
//ArithmeticException其實為運行時異常(RuntimeException),即使不進行throws聲明,也可以通過編譯
public int run(int m,int n)throws ArithmeticException,NegativeException{
if(n==0){
throw new ArithmeticException("除數(shù)不能為0");
}else if(n<0){
throw new NegativeException("除數(shù)不能為負數(shù)");
}
int s = m/n;
return s ;
}
@Override
public void method() {
try {
int p = 4/0;
} catch (ArithmeticException e) {
e.printStackTrace();
throw new RuntimeException();//將異常繼續(xù)拋出為運行時異常
}
}
}
感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
相關文章
Springboot下使用Redis管道(pipeline)進行批量操作
本文主要介紹了Spring?boot?下使用Redis管道(pipeline)進行批量操作,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2023-05-05

